package com.onlineMIS.ORM.DAO.headQ.inventoryFlow;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.onlineMIS.ORM.DAO.Response;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.BrandDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.CategoryDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.ProductBarcodeDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.ProductBarcodePicDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.QuarterDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.YearDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.inventory.InventoryOrderDAOImpl;
import com.onlineMIS.ORM.DAO.headQ.inventory.InventoryOrderProductDAOImpl;
import com.onlineMIS.ORM.DAO.headQ.supplier.purchase.HeadqPurchaseHistoryDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.supplier.purchase.PurchaseOrderProductDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.user.UserInforDaoImpl;
import com.onlineMIS.ORM.entity.base.BaseOrder;
import com.onlineMIS.ORM.entity.chainS.inventoryFlow.ChainInventoryFlowOrder;
import com.onlineMIS.ORM.entity.chainS.sales.ChainStoreSalesOrder;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Brand;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Category;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Color;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.ComboboxVO;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Product;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.ProductBarcode;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.ProductBarcodePic;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Quarter;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Year;
import com.onlineMIS.ORM.entity.headQ.inventory.InventoryBO;
import com.onlineMIS.ORM.entity.headQ.inventory.InventoryFileTemplate;
import com.onlineMIS.ORM.entity.headQ.inventory.InventoryOrder;
import com.onlineMIS.ORM.entity.headQ.inventory.InventoryOrderProductsVO;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadQInventoryStock;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadQInventoryStore;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadqInvenFlowOrderVO;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadqInvenTraceInfoTemplate;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadqInvenTraceInfoVO;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadqInventoryChangeReportTemplate;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadqInventoryDTO;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadqInventoryFlowOrder;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadqInventoryFlowOrderProduct;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadqInventoryFlowOrderTemplate;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadqInventoryReportItem;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadqInventoryReportTemplate;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadqInventoryVO;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HqInventoryChangeDetailsVO;
import com.onlineMIS.ORM.entity.headQ.supplier.purchase.HeadqPurchaseHistory;
import com.onlineMIS.ORM.entity.headQ.supplier.purchase.PurchaseOrder;
import com.onlineMIS.ORM.entity.headQ.user.UserInfor;
import com.onlineMIS.action.headQ.inventoryFlow.HeadqInventoryFlowFormBean;
import com.onlineMIS.action.headQ.inventoryFlow.HeadqInventoryFlowUIBean;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.DateUtils;
import com.onlineMIS.common.ExcelUtil;
import com.onlineMIS.common.LoginUserUtils;
import com.onlineMIS.common.loggerLocal;

@Service
public class HeadqInventoryFlowService {
	@Autowired
	private HeadQInventoryStockDAOImpl headQInventoryStockDAOImpl;
	@Autowired
	private YearDaoImpl yearDaoImpl;
	@Autowired
	private QuarterDaoImpl quarterDaoImpl;
	@Autowired
	private BrandDaoImpl brandDaoImpl;
	@Autowired
	private ProductBarcodeDaoImpl productBarcodeDaoImpl;
	@Autowired
	private HeadQInventoryStoreDAOImpl headQInventoryStoreDAOImpl;
	@Autowired
	private HeadQInventoryFlowOrderDAOImpl headqInventoryFlowOrderDaoImpl;
	@Autowired
	private HeadQInventoryFlowOrderProductDAOImpl headqInventoryFlowOrderProductDaoImpl;
	@Autowired
	private HeadqPurchaseHistoryDaoImpl headqPurchaseHistoryDaoImpl;
	@Autowired
	private UserInforDaoImpl userInforDaoImpl;
	@Autowired
	CategoryDaoImpl categoryDaoImpl;
	@Autowired
	InventoryOrderDAOImpl inventoryOrderDAOImpl;
	@Autowired
	private LoginUserUtils loginUserUtils;
	@Autowired
	private ProductBarcodePicDaoImpl productBarcodePicDaoImpl;
	@Autowired
	private PurchaseOrderProductDaoImpl purchaseOrderProductDaoImpl;
	@Autowired
	private InventoryOrderProductDAOImpl inventoryOrderProductDAOImpl;
	@Autowired
	private HeadQInventoryFlowOrderProductDAOImpl headQInventoryFlowOrderProductDAOImpl;
	/**
	 * 获取总部的库存状况
	 * 
	 * @param parentId
	 * @param storeId
	 * @param yearId
	 * @param quarterId
	 * @param brandId
	 * @return
	 */
	@Transactional
	public Response getHeadqInventory(int parentId, int storeId, int yearId, int quarterId, int brandId,
			int categoryLevelId, int categoryId, int rptTypeId,int belongTo,UserInfor userInfor) {
		System.out.println(storeId + "," + yearId + "," + quarterId + "," + brandId);
		Response response = new Response();
		List<HeadqInventoryVO> headqInventoryVOList = new ArrayList<HeadqInventoryVO>();
		if (parentId == 0) {
			//首行合计信息
						String hql;
						List<Object> inventoryData = new ArrayList<Object>();
							
						if (storeId != Common_util.ALL_RECORD) {
							hql = "SELECT  SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE his.storeId = ?  AND his.productBarcode.product.brand.belong_To = ?  ";
							Object[] values = { storeId,belongTo};
							inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
						} else {
							hql = "SELECT SUM(costTotal), SUM(salePriceTotal),SUM(quantity) FROM HeadQInventoryStock AS his WHERE  his.productBarcode.product.brand.belong_To = ? ";
							Object[] values = {belongTo};
							inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
						}

						if (inventoryData != null) {
							for (Object object : inventoryData) {
								Object[] object2 = (Object[]) object;
								
								double costTotal = Common_util.getDouble(object2[0]);
								double wholeSalePrice = Common_util.getDouble(object2[1]);
								int quantity = Common_util.getInt(object2[2]);
					
								HeadqInventoryVO headqInventoryVO = new HeadqInventoryVO(parentId +1, "合计", quantity,
										costTotal, HeadqInventoryVO.STATE_CLOSED, storeId, 0, quarterId, brandId, categoryId,
										categoryLevelId);
								headqInventoryVO.setWholeSalePrice(wholeSalePrice);
								headqInventoryVOList.add(headqInventoryVO);
							}
						}
		}else if (yearId == 0) {
			// @2. 展开所有年份的库存信息
			String hql;
			List<Object> inventoryData = new ArrayList<Object>();
				
			if (storeId != Common_util.ALL_RECORD) {
				hql = "SELECT his.productBarcode.product.year.year_ID, SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE his.storeId = ?  AND his.productBarcode.product.brand.belong_To = ?  GROUP BY his.productBarcode.product.year.year_ID ORDER BY his.productBarcode.product.year.year_ID ASC";
				Object[] values = { storeId,belongTo};
				inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
			} else {
				hql = "SELECT his.productBarcode.product.year.year_ID, SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE  his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.year.year_ID ORDER BY his.productBarcode.product.year.year_ID ASC";
				Object[] values = {belongTo};
				inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
			}

			if (inventoryData != null) {
				for (Object object : inventoryData) {
					Object[] object2 = (Object[]) object;
					int yearIdDB = Common_util.getInt(object2[0]);
					double costTotal = Common_util.getDouble(object2[1]);
					double wholeSalePrice = Common_util.getDouble(object2[1]);
					int quantity = Common_util.getInt(object2[3]);

					Year year = yearDaoImpl.get(yearIdDB, true);

					HeadqInventoryVO headqInventoryVO = new HeadqInventoryVO(parentId, year.getYear() + "年", quantity,
							costTotal, HeadqInventoryVO.STATE_CLOSED, storeId, yearIdDB, quarterId, brandId, categoryId,
							categoryLevelId);
					headqInventoryVO.setWholeSalePrice(wholeSalePrice);
					headqInventoryVOList.add(headqInventoryVO);
				}
			}
		} else if (quarterId == 0) {
			// @2. 展开所有季的库存信息
			String hql;
			//货品归属
			List<Object> inventoryData = new ArrayList<Object>();
			if (storeId != Common_util.ALL_RECORD) {
				hql = "SELECT his.productBarcode.product.quarter.quarter_ID, SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE his.storeId = ? AND his.productBarcode.product.brand.belong_To = ? AND his.productBarcode.product.year.year_ID=? GROUP BY his.productBarcode.product.quarter.quarter_ID ORDER BY his.productBarcode.product.quarter.quarter_ID ASC";
				Object[] values = { storeId, belongTo,yearId};
				inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
			} else {
				hql = "SELECT his.productBarcode.product.quarter.quarter_ID, SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.quarter.quarter_ID ORDER BY his.productBarcode.product.quarter.quarter_ID ASC";
				Object[] values = { yearId,belongTo };
				inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
			}

			if (inventoryData != null) {
				for (Object object : inventoryData) {
					Object[] object2 = (Object[]) object;
					int quarterIdDB = Common_util.getInt(object2[0]);
					double costTotal = Common_util.getDouble(object2[1]);
					double wholeSalePrice = Common_util.getDouble(object2[2]);
					int quantity = Common_util.getInt(object2[3]);

					Year year = yearDaoImpl.get(yearId, true);
					Quarter quarter = quarterDaoImpl.get(quarterIdDB, true);

					String name = year.getYear() + "年" + quarter.getQuarter_Name();

					HeadqInventoryVO headqInventoryVO = new HeadqInventoryVO(parentId, name, quantity, costTotal,
							HeadqInventoryVO.STATE_CLOSED, storeId, yearId, quarterIdDB, brandId, categoryId,
							categoryLevelId);
					headqInventoryVO.setWholeSalePrice(wholeSalePrice);
					headqInventoryVOList.add(headqInventoryVO);
				}
			}
		} else {
			// by brand
			if (rptTypeId == 1) {
				if (brandId == 0) {
					// @2. 展开所有品霞的库存信息
					String hql;
					List<Object> inventoryData = new ArrayList<Object>();

					if (storeId != Common_util.ALL_RECORD) {
						hql = "SELECT his.productBarcode.product.brand.brand_ID, SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE his.storeId = ? AND his.productBarcode.product.brand.belong_To = ? AND his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? GROUP BY his.productBarcode.product.brand.brand_ID ORDER BY his.productBarcode.product.brand.brand_ID ASC";
						Object[] values = { storeId,belongTo, yearId, quarterId };
						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					} else {
						hql = "SELECT his.productBarcode.product.brand.brand_ID, SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE  his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=?  AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.brand.brand_ID ORDER BY his.productBarcode.product.brand.brand_ID ASC";
						Object[] values = { yearId, quarterId ,belongTo};
						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					}

					if (inventoryData != null) {
						for (Object object : inventoryData) {
							Object[] object2 = (Object[]) object;
							int brandIdDB = Common_util.getInt(object2[0]);
							double costTotal = Common_util.getDouble(object2[1]);
							double wholeSalePrice = Common_util.getDouble(object2[2]);
							int quantity = Common_util.getInt(object2[3]);

							Brand brand = brandDaoImpl.get(brandIdDB, true);

							String name = "";
							String pinyin = brand.getPinyin();
							if (!StringUtils.isEmpty(pinyin)) {
								name = pinyin.substring(0, 1) + " ";
							}

							name = brand.getBrand_Name();

							HeadqInventoryVO headqInventoryVO = new HeadqInventoryVO(parentId, name, quantity,
									costTotal, HeadqInventoryVO.STATE_CLOSED, storeId, yearId, quarterId, brandIdDB,
									categoryId, categoryLevelId);
							headqInventoryVO.setWholeSalePrice(wholeSalePrice);
							headqInventoryVOList.add(headqInventoryVO);
						}
					}
				} else if (brandId != 0) {
					// @2. 展开当前品霞的库存信息
					String hql;
					List<Object> inventoryData = new ArrayList<Object>();

					if (storeId != Common_util.ALL_RECORD) {
						hql = "SELECT his.productBarcode.id, SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE his.storeId = ? AND his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.brand.brand_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.id ORDER BY his.productBarcode.product.productCode ASC ";
						Object[] values = { storeId, yearId, quarterId, brandId ,belongTo};
						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					} else {
						hql = "SELECT his.productBarcode.id, SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.brand.brand_ID=?  AND his.productBarcode.product.brand.belong_To = ?  GROUP BY his.productBarcode.id ORDER BY his.productBarcode.product.productCode ASC ";
						Object[] values = { yearId, quarterId, brandId ,belongTo};
						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					}

					if (inventoryData != null) {
						for (Object object : inventoryData) {
							Object[] object2 = (Object[]) object;
							int pbId = Common_util.getInt(object2[0]);
							double costTotal = Common_util.getDouble(object2[1]);
							double wholeSalePrice = Common_util.getDouble(object2[2]);
							int quantity = Common_util.getInt(object2[3]);

							ProductBarcode pb = productBarcodeDaoImpl.get(pbId, true);
							Color color = pb.getColor();
							String colorName = "";
							if (color != null)
								colorName = color.getName();
							Product product = pb.getProduct();
							String gender = "";
							String sizeRange = "";

							Category category = product.getCategory();
							String name = Common_util.cutProductCode(pb.getProduct().getProductCode()) + colorName + " "
									+ gender + sizeRange + category.getCategory_Name();
							
							String imgMsg = "";
							String imgPath = productBarcodePicDaoImpl.getURLPathByBarcode(pb.getBarcode(), ProductBarcodePic.TYPE_PING_MIAN_PIC);
							
							if (imgPath != null) {
								imgMsg = "详情";
							}

							HeadqInventoryVO headqInventoryVO = new HeadqInventoryVO(parentId, name, quantity,
									costTotal, HeadqInventoryVO.STATE_OPEN, storeId, yearId, quarterId, brandId,
									categoryId, categoryLevelId);
							headqInventoryVO.setWholeSalePrice(wholeSalePrice);
							headqInventoryVO.setPbId(pbId);
							headqInventoryVO.setBarcode(pb.getBarcode());
							headqInventoryVO.setSize(pb.getProduct().getSizeMin() + "-" +pb.getProduct().getSizeMax());
							headqInventoryVO.setSalesPrice(pb.getProduct().getSalesPrice()*quantity);
							headqInventoryVO.setImgPath(imgMsg);
							headqInventoryVOList.add(headqInventoryVO);
						}
					}
				}
			} else if (rptTypeId == 2) {

				if (categoryLevelId == 0) {
					// @2. 展开所有品类的库存信息
					String hql;
					List<Object> inventoryData = new ArrayList<Object>();
					if (storeId != Common_util.ALL_RECORD) {
						hql = "SELECT his.productBarcode.product.categoryLevel1.category_ID, SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE his.storeId = ?  AND his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.categoryLevel1.category_ID";
						Object[] values = { storeId, yearId, quarterId ,belongTo};
						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					} else {
						hql = "SELECT his.productBarcode.product.categoryLevel1.category_ID, SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE  his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.categoryLevel1.category_ID";
						Object[] values = { yearId, quarterId,belongTo };
						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					}

					if (inventoryData != null) {
						for (Object object : inventoryData) {
							Object[] object2 = (Object[]) object;
							int categoryLevel1Id = Common_util.getInt(object2[0]);
							double costTotal = Common_util.getDouble(object2[1]);
							double wholeSalePrice = Common_util.getDouble(object2[2]);
							int quantity = Common_util.getInt(object2[3]);

							Category catgory = categoryDaoImpl.get(categoryLevel1Id, true);
							String name = catgory.getCategory_Name();

							HeadqInventoryVO headqInventoryVO = new HeadqInventoryVO(parentId, name, quantity,
									costTotal, HeadqInventoryVO.STATE_CLOSED, storeId, yearId, quarterId, brandId,
									categoryId, categoryLevel1Id);
							headqInventoryVO.setWholeSalePrice(wholeSalePrice);
							headqInventoryVOList.add(headqInventoryVO);
						}
					}
				} else if (categoryId == 0) {

					// @2. 展开所有品类的库存信息 表示 categoryLevel1 != 0

					String hql;
					List<Object> inventoryData = new ArrayList<Object>();

					if (storeId == Common_util.ALL_RECORD) {
						hql = "SELECT his.productBarcode.product.category.category_ID, SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.category.category_ID ORDER BY SUM(quantity) DESC";
						Object[] values = { yearId, quarterId, categoryLevelId,belongTo };

						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					} else {
						hql = "SELECT his.productBarcode.product.category.category_ID, SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE his.storeId = ? AND   his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.category.category_ID SUM(quantity) DESC";
						Object[] values = { storeId, yearId, quarterId, categoryLevelId ,belongTo};

						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					}

					if (inventoryData != null) {
						for (Object object : inventoryData) {
							Object[] object2 = (Object[]) object;
							int categoryIdDB = Common_util.getInt(object2[0]);
							double costTotal = Common_util.getDouble(object2[1]);
							double wholeSalePrice = Common_util.getDouble(object2[2]);
							int quantity = Common_util.getInt(object2[3]);

							Category catgory = categoryDaoImpl.get(categoryIdDB, true);
							String name = catgory.getCategory_Name();

							HeadqInventoryVO headqInventoryVO = new HeadqInventoryVO(parentId, name, quantity,
									costTotal, HeadqInventoryVO.STATE_CLOSED, storeId, yearId, quarterId, brandId,
									categoryIdDB, categoryLevelId);
							headqInventoryVO.setWholeSalePrice(wholeSalePrice);
							headqInventoryVOList.add(headqInventoryVO);
						}
					}
				} else {
					// @2. 展开当前品霞的库存信息
					String hql;
					List<Object> inventoryData = new ArrayList<Object>();
					if (storeId == Common_util.ALL_RECORD) {
						hql = "SELECT his.productBarcode.id, SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE  his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND  his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.category.category_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.id ORDER BY SUM(quantity) DESC";
						Object[] values = {yearId, quarterId, categoryLevelId, categoryId ,belongTo};

						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					} else {
						hql = "SELECT his.productBarcode.id, SUM(costTotal),SUM(salePriceTotal), SUM(quantity) FROM HeadQInventoryStock AS his WHERE his.storeId = ? AND  his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND  his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.category.category_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.id ORDER BY SUM(quantity) DESC";
						Object[] values = {storeId,  yearId, quarterId, categoryLevelId, categoryId ,belongTo};

						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					}

					if (inventoryData != null) {
						for (Object object : inventoryData) {
							Object[] object2 = (Object[]) object;
							int pbId = Common_util.getInt(object2[0]);
							double costTotal = Common_util.getDouble(object2[1]);
							double wholeSalePrice = Common_util.getDouble(object2[2]);
							int quantity = Common_util.getInt(object2[3]);

							ProductBarcode pb = productBarcodeDaoImpl.get(pbId, true);
							Color color = pb.getColor();
							String colorName = "";
							if (color != null)
								colorName = color.getName();

							Brand brand = pb.getProduct().getBrand();
							String name = Common_util.cutProductCode(pb.getProduct().getProductCode()) + colorName + " "
									+ brand.getBrand_Name();
							
							String imgMsg = "";
							String imgPath = productBarcodePicDaoImpl.getURLPathByBarcode(pb.getBarcode(), ProductBarcodePic.TYPE_PING_MIAN_PIC);
							
							if (imgPath != null) {
								imgMsg = "详情";
							}

							HeadqInventoryVO headqInventoryVO = new HeadqInventoryVO(parentId, name, quantity,
									costTotal, HeadqInventoryVO.STATE_OPEN, storeId, yearId, quarterId, brandId,
									categoryId, categoryLevelId);
							headqInventoryVO.setPbId(pbId);
							headqInventoryVO.setBarcode(pb.getBarcode());
							headqInventoryVO.setWholeSalePrice(wholeSalePrice);
							headqInventoryVO.setImgPath(imgMsg);
							headqInventoryVOList.add(headqInventoryVO);

						}
					}
				}
			}
		}
		if (headqInventoryVOList.size() != 0) {
			//查看成本权限
			if (!loginUserUtils.hasPermissionOnCost(userInfor)) {
				for (HeadqInventoryVO headqInventoryVO : headqInventoryVOList) {
					headqInventoryVO.setRecCost(0);
				}
			}
		}

		response.setReturnValue(headqInventoryVOList);
		return response;
	}

	/**
	 * 生成excel的inventory 报表
	 * 
	 * @param storeId
	 * @param yearId
	 * @param quarterId
	 * @param brandId
	 * @param string
	 * @return
	 * @throws IOException
	 */
	public Response generateInventoryExcelReport(int belongTo,int storeId, int yearId, int quarterId, int brandId,int pbId,
			String templatePath,UserInfor userInfor) {
		Response response = new Response();
		HeadQInventoryStore store = null;
		if (storeId != Common_util.ALL_RECORD) {
			store = headQInventoryStoreDAOImpl.get(storeId, true);
		} else {
			store = new HeadQInventoryStore();
			store.setName("所有库房");
			store.setComment("所有仓库");
		}

		List<HeadqInventoryReportItem> reportItems = new ArrayList<HeadqInventoryReportItem>();
		StringBuffer hql = new StringBuffer(
				"SELECT his.productBarcode.id, SUM(quantity),his.cost, SUM(costTotal),his.salePrice,SUM(salePriceTotal) FROM HeadQInventoryStock AS his WHERE his.productBarcode.product.brand.belong_To=" + belongTo);
			
		if (brandId != 0) {
			hql.append(" AND his.productBarcode.product.brand.brand_ID=" + brandId);
		}
		if (quarterId != 0) {
			hql.append(" AND his.productBarcode.product.quarter.quarter_ID=" + quarterId);
		}
		if (yearId != 0) {
			hql.append(" AND his.productBarcode.product.year.year_ID=" + yearId);
		}
		if(pbId !=0) {
			hql.append(" AND his.productBarcode.id=" + pbId);
		}
		if (storeId != Common_util.ALL_RECORD) {
			hql.append(" AND his.storeId=" + storeId);
		}
		hql.append(" GROUP BY his.productBarcode.id");

		List<Object> result = headQInventoryStockDAOImpl.executeHQLSelect(hql.toString(), null, null, true);
		for (int i = 0; i < result.size(); i++) {
			Object object = result.get(i);
			if (object != null) {
				HeadqInventoryReportItem item = new HeadqInventoryReportItem();

				Object[] recordResult = (Object[]) object;
				int productId = Common_util.getInt(recordResult[0]);
				int quantity = Common_util.getInt(recordResult[1]);
				double cost = 0;
				double totalCost = 0;
				//是否督导
				if (loginUserUtils.hasPermissionOnCost(userInfor)) {
					cost = Common_util.getDouble(recordResult[2]);
					totalCost = Common_util.getDouble(recordResult[3]);
				}
				double wholeSales = Common_util.getDouble(recordResult[4]);
				double totalWholeSalesAmt = Common_util.getDouble(recordResult[5]);

				if (quantity == 0)
					continue;
				item.setTotalQuantity(quantity);
				item.setCost(cost);
				item.setTotalCostAmt(totalCost);
				item.setWholeSales(wholeSales);
				item.setTotalWholeSalesAmt(totalWholeSalesAmt);

				ProductBarcode productBarcode = productBarcodeDaoImpl.get(productId, true);
				item.setProductBarcode(productBarcode);
				reportItems.add(item);
			}
		}

		// Collections.sort(reportItems, new HeadqInventoryReportSort());
		HeadqInventoryReportTemplate headqInventoryReportTemplate;
		try {
			headqInventoryReportTemplate = new HeadqInventoryReportTemplate(reportItems, store, templatePath);
			HSSFWorkbook wb = headqInventoryReportTemplate.process();

			ByteArrayInputStream byteArrayInputStream = ExcelUtil.convertExcelToInputStream(wb);

			response.setReturnValue(byteArrayInputStream);
			response.setReturnCode(Response.SUCCESS);
		} catch (IOException e) {
			response.setFail(e.getMessage());
			e.printStackTrace();
		}

		return response;
	}

	/**
	 * 获取库存跟踪信息
	 * 
	 * @param storeId
	 * @param pbId
	 * @return
	 */
	public Response getInventoryTraceInfor(int storeId, int pbId) {
		Response response = new Response();
		Map data = new HashMap<String, List>();
		List<HeadqInvenTraceInfoVO> traceVOs = new ArrayList<HeadqInvenTraceInfoVO>();
		List<HeadqInvenTraceInfoVO> footers = new ArrayList<HeadqInvenTraceInfoVO>();

		DetachedCriteria criteria1 = DetachedCriteria.forClass(HeadQInventoryStock.class);
		if (storeId != Common_util.ALL_RECORD) {
			criteria1.add(Restrictions.eq("storeId", storeId));
		}

		if (pbId != Common_util.ALL_RECORD_NEW) {
			criteria1.add(Restrictions.eq("productBarcode.id", pbId));
		}			
		
		
		criteria1.addOrder(Order.asc("date"));
		List<HeadQInventoryStock> stocks = headQInventoryStockDAOImpl.getByCritera(criteria1, true);

		for (HeadQInventoryStock stock : stocks) {
			int storeIdDB = stock.getStoreId();
			HeadQInventoryStore store = headQInventoryStoreDAOImpl.get(storeIdDB, false);
			HeadqInvenTraceInfoVO traceVO = new HeadqInvenTraceInfoVO(stock, store.getName());
			traceVOs.add(traceVO);
		}

		// 建设foot
		HeadqInvenTraceInfoVO foot = new HeadqInvenTraceInfoVO();
		int stockInventory = 0;
		for (HeadqInvenTraceInfoVO ele : traceVOs) {
			stockInventory += ele.getQuantity();
		}

		if (pbId !=  Common_util.ALL_RECORD_NEW) {
			ProductBarcode pb = productBarcodeDaoImpl.get(pbId, true);
			String productName = pb.getProduct().getBrand().getBrand_Name() + " " + pb.getProduct().getProductCode();
			Color color = pb.getColor();
			if (color != null)
				productName += color.getName();

			foot.setDate(productName);
			foot.setQuantity(stockInventory);
			footers.add(foot);
		}
		

		response.setReturnCode(Response.SUCCESS);

		data.put("rows", traceVOs);
		data.put("footer", footers);
		response.setReturnValue(data);

		return response;
	}
	
	
	/**
	 * 获取库存跟踪信息
	 * 
	 * @param storeId
	 * @param pbId
	 * @return
	 */
	public Response getInventoryHistory(java.sql.Date startDate, java.sql.Date endDate,int storeId, String barcode) {
		Response response = new Response();
		Map data = new HashMap<String, List>();
		List<HeadqInvenTraceInfoVO> traceVOs = new ArrayList<HeadqInvenTraceInfoVO>();
		List<HeadqInvenTraceInfoVO> footers = new ArrayList<HeadqInvenTraceInfoVO>();
		if (StringUtils.isNotBlank(barcode)) {
			traceVOs = selectInventotyStocks(startDate,endDate,storeId,barcode);
		}
		// 建设foot
		HeadqInvenTraceInfoVO foot = new HeadqInvenTraceInfoVO();
		int stockInventory = 0;
		for (HeadqInvenTraceInfoVO ele : traceVOs) {
			stockInventory += ele.getQuantity();
		}
		foot.setBarcode("合计");
		foot.setQuantity(stockInventory);
		footers.add(foot);
		
		response.setReturnCode(Response.SUCCESS);

		data.put("rows", traceVOs);
		data.put("footer", footers);
		response.setReturnValue(data);

		return response;
	}
	
	
	/**
	 * 根据库房和条码查询货品跟踪记录
	 * @param storeId
	 * @param barcode
	 * @return
	 */
	public List<HeadqInvenTraceInfoVO> selectInventotyStocks(java.sql.Date startDate, java.sql.Date endDate,int storeId, String barcode) {
		List<HeadqInvenTraceInfoVO> traceVOs = new ArrayList<HeadqInvenTraceInfoVO>();

		DetachedCriteria criteria1 = DetachedCriteria.forClass(HeadQInventoryStock.class);
		if (storeId != Common_util.ALL_RECORD) {
			criteria1.add(Restrictions.eq("storeId", storeId));
		}
		ProductBarcode pBarcode = productBarcodeDaoImpl.getByBarcode(barcode);
		if (pBarcode != null) {
			criteria1.add(Restrictions.eq("productBarcode.id", pBarcode.getId()));
			criteria1.add(Restrictions.between("date", Common_util.formStartDate(startDate), Common_util.formEndDate(endDate)));
			criteria1.addOrder(Order.desc("date"));
			List<HeadQInventoryStock> stocks = headQInventoryStockDAOImpl.getByCritera(criteria1, true);
						
			for (HeadQInventoryStock stock : stocks) {
				
				HeadQInventoryStore store = headQInventoryStoreDAOImpl.get(stock.getStoreId(), true);
				HeadqInvenTraceInfoVO traceVO = new HeadqInvenTraceInfoVO(stock,pBarcode, store.getName());			
				traceVO.setDiscount(stock.getDiscount());
				if (traceVO.isDetails()) {
					InventoryOrder order = inventoryOrderDAOImpl.get(Integer.valueOf(traceVO.getOrderId()), true);
					if (order != null) {
						traceVO.setClientName(order.getClient_name());
					}
				}
				traceVOs.add(traceVO);
			}
		}
		return traceVOs;
	}
	

	/**
	 * 准备报损单 报溢单 页面
	 * 
	 * @param formBean
	 */
	public void prepareCreateOrderUI(HeadqInventoryFlowFormBean formBean, HeadqInventoryFlowUIBean uiBean,
			UserInfor loginUser) {
		// 2. set the creator
		formBean.getFlowOrder().setCreator(loginUser);

		// 3. set the date
		formBean.getFlowOrder().setOrderDate(new Date());

		List<HeadQInventoryStore> stores = headQInventoryStoreDAOImpl.getAll(true);
		uiBean.setStores(stores);

	}

	/**
	 * 在inventory flow order上 scan barcode
	 * 
	 * @param barcode
	 * @param indexPage
	 * @param fromSrc
	 * @return
	 */
	public Response scanByBarcodeInvenOrder(String barcode, int indexPage, int fromSrc, int storeId) {
		Response response = new Response();
		ProductBarcode pb = productBarcodeDaoImpl.getByBarcode(barcode);

		if (pb != null) {

			productBarcodeDaoImpl.evict(pb);

			int inventoryLevel = 0;

			try {
				inventoryLevel = headQInventoryStockDAOImpl.getProductStock(pb.getId(), storeId, true);
			} catch (Exception e) {
				String msg = "获取inventory出错," + pb.getId() + "," + storeId;
				loggerLocal.info(msg);
				response.setFail(msg);
				return response;
			}

			HeadqInventoryFlowProductVO productVO = new HeadqInventoryFlowProductVO(pb, inventoryLevel, indexPage);
			response.setReturnValue(productVO);

			return response;
		} else {
			HeadqInventoryFlowProductVO productVO = new HeadqInventoryFlowProductVO(null, 0, indexPage);
			response.setReturnValue(productVO);

			response.setFail("无法找到条码 : " + barcode);
			return response;
		}

	}

	/**
	 * function to save the flow order to draft order 保存草稿
	 * 
	 * @param flowOrder
	 * @throws Exception
	 */
	@Transactional
	public Response saveToDraft(HeadqInventoryFlowOrder flowOrder, File file,String jsons, UserInfor loginUser) throws Exception {
		int status_org = flowOrder.getStatus();
		Response response = new Response();
		//填充:将json字符串转对象集合
		fillFlowOrder(flowOrder, jsons);
		//是否调货单
		if (flowOrder.getType() == HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER) {		
			//校验调入和调出库房是否是同一归属库房
			HeadQInventoryStore fromStore = headQInventoryStoreDAOImpl.get(flowOrder.getFromStore().getId(), true);
			HeadQInventoryStore toStore = headQInventoryStoreDAOImpl.get(flowOrder.getToStore().getId(), true);
			if (fromStore != null && toStore !=null && fromStore.getBelongTo() == toStore.getBelongTo()) {
				flowOrder.setStoreId(flowOrder.getFromStore().getId());
			}else {
				save(flowOrder, loginUser);
				response.setFail("调出库房："+fromStore.getName() + " 和 调入库房：" + toStore.getName() + "并不是同一归属的库房,请重新选择");
				return response;
			}
		} else {
			flowOrder.setStoreId(flowOrder.getStoreId());
		}

		//是否初始状态或草稿状态
		if (status_org == HeadqInventoryFlowOrder.STATUS_INITIAL || status_org == HeadqInventoryFlowOrder.STATUS_DRAFT) {
			flowOrder.setStatus(HeadqInventoryFlowOrder.STATUS_DRAFT);

			List<HeadqInventoryFlowOrderProduct> products = null;
			
			boolean isFileError = false;
			try {
				products = parseInventoryFile(file);
			} catch (Exception e) {
				response.setQuickValue(Response.FAIL, "库存文件格式错误");
				isFileError = true;
			}
			

			List<HeadqInventoryFlowOrderProduct> currentProducts = flowOrder.getProductList();
			
			if (isFileError && currentProducts.size() != 0) {
				//校验货品是否归属该库房
				response =  isCheckProduct(flowOrder);
				if (response.getReturnCode() == Response.FAIL) {
					save(flowOrder, loginUser);
					return response;
				}
				save(flowOrder, loginUser);
				response.setFail("经扫描的条码信息已存入草稿，而附带上传的文件存在文件格式错误，所以文件条码信息未录入草稿单据");	
				return response;
			}else {
				currentProducts.addAll(products);
			}
									
			//校验货品是否归属该库房
			response =  isCheckProduct(flowOrder);
			if (response.getReturnCode() == Response.FAIL) {
				save(flowOrder, loginUser);
				return response;
			}
			save(flowOrder, loginUser);
			response.setSuccess("保存草稿成功");					
		} else {
			response.setFail("保存草稿失败");
		}
		return response;

	}
	
	/**
	 * headqInventoryFlowOrder填充productList
	 * @param flowOrder
	 * @param jsons
	 */
	private void fillFlowOrder(HeadqInventoryFlowOrder flowOrder,String jsons) {
		if(StringUtils.isNotBlank(jsons)) {
			List<InventoryBO> list = (List<InventoryBO>)net.sf.json.JSONArray.toList(net.sf.json.JSONArray.fromObject(jsons),InventoryBO.class);
			List<HeadqInventoryFlowOrderProduct> ps = new ArrayList<HeadqInventoryFlowOrderProduct>();
			if (list.size() !=0) {
				for (InventoryBO bo : list) {
					HeadqInventoryFlowOrderProduct product = new HeadqInventoryFlowOrderProduct();
					ProductBarcode productBarcode = productBarcodeDaoImpl.get(Integer.valueOf(bo.getPbId()), true);
					ProductBarcode barcode = new ProductBarcode();
					barcode.setId(Integer.valueOf(bo.getPbId()));
					barcode.setBarcode(bo.getBarcode());
					barcode.setProduct(productBarcode.getProduct());
					product.setProductBarcode(barcode);
					product.setQuantity(Integer.valueOf(bo.getNums()));
					product.setScanNums(Integer.valueOf(bo.getScanNums()));
					if (StringUtils.isNotBlank(bo.getComment())) {
						product.setComment(bo.getComment());
					}else {
						product.setComment("");
					}
					ps.add(product);
				}
				flowOrder.setProductList(ps);
			}
		}
	}
	
	
	
	/**
	 * 校验货品归属是否和库房归属是否统一
	 * @param flowOrder
	 * @return
	 */
	private Response isCheckProduct(HeadqInventoryFlowOrder flowOrder) {
		Response response = new Response();
		List<String> barcodes = new ArrayList<String>();
		List<ProductBarcode> pList = new ArrayList<ProductBarcode>();
		String errMsg = "";
		String belongTos = "";
		if (flowOrder.getProductList().size() !=0) {
			for (HeadqInventoryFlowOrderProduct product : flowOrder.getProductList()) {
				if (product != null && !product.getProductBarcode().getBarcode().equals("")) {
					barcodes.add(product.getProductBarcode().getBarcode());
				}				
			}
			
		}
		pList = productBarcodeDaoImpl.selectProductBarcodes(barcodes);
		
		HeadQInventoryStore store = headQInventoryStoreDAOImpl.get(flowOrder.getStoreId(), true);		
		if (store != null) {
			int belongTo = store.getBelongTo();
			Brand brand = new Brand();
			belongTos = brand.belongToMap.get(belongTo);
			if (pList != null) {
				for (ProductBarcode productBarcode : pList) {
					int productBelongTo = productBarcode.getProduct().getBrand().getBelong_To();
					if (productBelongTo != belongTo) {
						errMsg += productBarcode.getBarcode() + ",";
					}
				}
			}
		}
		
		if (errMsg.length() !=0) {
			response.setFail("以下货品并不是"+belongTos + "货品,所以无法选择"+store.getName()+",请剔除后重新提交单据" + ",具体条码如下：" + errMsg );
		}
		return response;
		
	}
	
	/**
	 * function to save the flow order to final 过账
	 * 
	 * @param flowOrder
	 * @param loginUser
	 * @throws Exception
	 */
	@Transactional
	public Response saveToFinal(HeadqInventoryFlowOrder order, File file,String jsons, UserInfor loginUser) throws Exception {
		int status_org = 0;
		Response response = new Response();
		//填充:将json字符串转对象集合
		fillFlowOrder(order, jsons);
		//读取文件信息
		List<HeadqInventoryFlowOrderProduct> products = null;
		boolean isFileError = false;
		try {
			products = parseInventoryFile(file);
		} catch (Exception e) {
			response.setQuickValue(Response.FAIL, "库存文件格式错误");
			isFileError = true;
		}
		List<HeadqInventoryFlowOrderProduct> currentProducts = order.getProductList();
		
		//是否调货单
		if (order.getType() == HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER) {									
			//校验调入和调出库房是否是同一归属库房
			HeadQInventoryStore fromStore = headQInventoryStoreDAOImpl.get(order.getFromStore().getId(), true);
			HeadQInventoryStore toStore = headQInventoryStoreDAOImpl.get(order.getToStore().getId(), true);
			if (fromStore != null && toStore !=null && fromStore.getBelongTo() == toStore.getBelongTo()) {
				order.setStoreId(order.getFromStore().getId());
			}else {
				order.setStatus(HeadqInventoryFlowOrder.STATUS_DRAFT);
				save(order, loginUser);
				response.setFail("调出库房："+fromStore.getName() + " 和 调入库房：" + toStore.getName() + "并不是同一归属的库房,请重新选择");
				return response;
			}
		} else {
			order.setStoreId(order.getStoreId());
		}	
				
		
		//校验货品是否归属该库房
		response =  isCheckProduct(order);
		if (response.getReturnCode() == Response.FAIL) {
			order.setStatus(HeadqInventoryFlowOrder.STATUS_DRAFT);
			save(order, loginUser);
			return response;
		}
		if (status_org == HeadqInventoryFlowOrder.STATUS_INITIAL || status_org == HeadqInventoryFlowOrder.STATUS_DRAFT) {
			if (order.getType() == HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER) {
				order.setStoreId(order.getFromStore().getId());
			}
			if (isFileError) {
				order.setStatus(HeadqInventoryFlowOrder.STATUS_DRAFT);
				// 总部 报溢 报损 库存转移单据过账
				save(order, loginUser);
				response.setFail("经扫描的条码信息已存入草稿，而附带上传的文件存在文件格式错误，所以文件条码信息未录入草稿单据");
			}else {
				currentProducts.addAll(products);	
				order.setStatus(HeadqInventoryFlowOrder.STATUS_COMPLETE);
				save(order, loginUser);
				// 报溢 报损
				if (order.getType() == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER || order.getType() == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {
					updateHeadqFlowOrderInOutStock(order, HeadqInventoryFlowOrder.STATUS_COMPLETE);				
				} else if (order.getType() == HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER) {// 调货单		
					updateHeadqInvenTransferInOutStock(order, HeadqInventoryFlowOrder.STATUS_COMPLETE);// 库存转移业务逻辑
				}
				response.setSuccess("保存单据成功");				
			}								
		} else {
			response.setFail("保存单据失败");
		}
		return response;
	}

	/**
	 * function to save the flow order to final 过账
	 * 
	 * @param flowOrder
	 * @param loginUser
	 * @throws Exception
	 */
	@Transactional
	public Response saveToFinal(HeadqInventoryFlowOrder order, UserInfor loginUser) throws Exception {
		int status_org = 0;
		Response response = new Response();
		//是否调货单
		if (order.getType() == HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER) {		
			//校验调入和调出库房是否是同一归属库房
			HeadQInventoryStore fromStore = headQInventoryStoreDAOImpl.get(order.getFromStore().getId(), true);
			HeadQInventoryStore toStore = headQInventoryStoreDAOImpl.get(order.getToStore().getId(), true);
			if (fromStore != null && toStore !=null && fromStore.getBelongTo() == toStore.getBelongTo()) {
				order.setStoreId(order.getFromStore().getId());
			}else {
				response.setFail("调出库房："+fromStore.getName() + " 和 调入库房：" + toStore.getName() + "并不是同一归属的库房,请重新选择");
				return response;
			}
		} else {
			order.setStoreId(order.getStoreId());
		}		
		//校验货品是否归属该库房
		response =  isCheckProduct(order);
		if (response.getReturnCode() == Response.FAIL) {
			return response;
		}
		if (status_org == HeadqInventoryFlowOrder.STATUS_INITIAL || status_org == HeadqInventoryFlowOrder.STATUS_DRAFT) {
			if (order.getType() == HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER) {
				order.setStoreId(order.getFromStore().getId());
			}
			order.setStatus(HeadqInventoryFlowOrder.STATUS_COMPLETE);
			// 总部 报溢 报损 库存转移单据过账
			save(order, loginUser);
			// 报溢 报损
			if (order.getType() == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER || order.getType() == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {
				updateHeadqFlowOrderInOutStock(order, HeadqInventoryFlowOrder.STATUS_COMPLETE);				
			} else if (order.getType() == HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER) {// 调货单		
				updateHeadqInvenTransferInOutStock(order, HeadqInventoryFlowOrder.STATUS_COMPLETE);// 库存转移业务逻辑
			}
			response.setSuccess("保存单据成功");
		} else {
			response.setFail("保存单据失败");
		}

		return response;
	}

	/**
	 * add the general save information
	 * 
	 * @param flowOrder
	 * @param loginUser
	 * @throws Exception
	 */
	@Transactional
	public HeadqInventoryFlowOrder save(HeadqInventoryFlowOrder flowOrder, UserInfor loginUser) throws Exception {
		flowOrder.setOrderDate(new Date());
		flowOrder.setCreator(loginUser);

		// 1. group productlist
		// 刷新库存
		groupProductList(flowOrder);

		// 2. 获取数据库最新的数据
		List<HeadqInventoryFlowOrderProduct> productList = flowOrder.getProductList();
		double totalCost = 0, totalWholePrice = 0;
		int totalInventoryQ = 0;
		for (HeadqInventoryFlowOrderProduct product : productList) {
			int pbId = product.getProductBarcode().getId();

			ProductBarcode pBarcode = productBarcodeDaoImpl.get(pbId, true);

			double wholePrice = ProductBarcodeDaoImpl.getWholeSalePrice(pBarcode);

			product.setWholePrice(wholePrice);
			product.setTotalWholePrice(wholePrice * product.getQuantity());

			double cost = pBarcode.getProduct().getRecCost();
			HeadqPurchaseHistory headqPurchaseHistory = headqPurchaseHistoryDaoImpl.get(pbId, true);
			if (headqPurchaseHistory != null)
				cost = headqPurchaseHistory.getRecCost();

			product.setCost(cost);
			product.setTotalCost(cost * product.getQuantity());

			totalCost += cost * product.getQuantity();
			totalWholePrice += wholePrice * product.getQuantity();
			int inventoryQ = headQInventoryStockDAOImpl.getProductStock(product.getProductBarcode().getId(),
					flowOrder.getStoreId(), true);
			product.setInventoryQ(inventoryQ);
			totalInventoryQ +=inventoryQ;
		}

		flowOrder.setTotalInventoryQ(totalInventoryQ);
		flowOrder.setTotalQuantityDiff(flowOrder.getTotalQuantity()-flowOrder.getTotalInventoryQ());
		flowOrder.setTotalCost(totalCost);
		flowOrder.setTotalWholePrice(totalWholePrice);
		flowOrder.buildIndex();
		flowOrder.putListToSet();
		flowOrder.setLastUpdateBy(LoginUserUtils.getName());
		flowOrder.setLastUpdateDate(DateUtils.getNowDate());

		int orderId = flowOrder.getId();

		if (orderId != 0) {

			HeadqInventoryFlowOrder originalOrder = getOrderById(orderId, loginUser);

			// orderId@orderProductId
			// 123@2345
			Set<Integer> newProducts = getProductIds(flowOrder);
			Set<Integer> originalProducts = getProductIds(originalOrder);
			Set<Integer> deletedProducts = new HashSet<Integer>();
			for (Integer id : originalProducts) {
				if (!newProducts.contains(id))
					deletedProducts.add(id);
			}
			headqInventoryFlowOrderProductDaoImpl.deleteProducts(orderId, deletedProducts);

			headqInventoryFlowOrderDaoImpl.evict(originalOrder);

			headqInventoryFlowOrderDaoImpl.saveOrUpdate(flowOrder, false);
		} else {
			headqInventoryFlowOrderDaoImpl.save(flowOrder, false);
		}

		return flowOrder;

	}

	/**
	 * to get the product ids
	 * 
	 * @param order
	 * @return
	 */
	private Set<Integer> getProductIds(HeadqInventoryFlowOrder order) {
		Set<Integer> originalProducts = new HashSet();
		if (order != null && order.getProductSet() != null)
			for (HeadqInventoryFlowOrderProduct orderProduct : order.getProductSet()) {
				if (orderProduct != null) {
					originalProducts.add(orderProduct.getProductBarcode().getId());
				}
			}

		return originalProducts;
	}

	@Transactional
	public HeadqInventoryFlowOrder getOrderById(int orderId, UserInfor loginUser) {
		HeadqInventoryFlowOrder order = headqInventoryFlowOrderDaoImpl.get(orderId, false);

		List<HeadqInventoryFlowOrderProduct> list = headQInventoryFlowOrderProductDAOImpl.selectProductsByOrderId(orderId);
		order.setProductList(list);	

		List<HeadqInventoryFlowOrderProduct> productList = order.getProductList();
		for (HeadqInventoryFlowOrderProduct product : productList) {

			int inventoryQ = headQInventoryStockDAOImpl.getProductStock(product.getProductBarcode().getId(),order.getStoreId(), true);
			product.setInventoryQ(inventoryQ);

		}

		return order;
	}

	/**
	 * function to updat the chain stock in/out level
	 * 
	 * @param order
	 * @param statusCancel
	 * @throws Exception
	 */
	private void updateHeadqFlowOrderInOutStock(HeadqInventoryFlowOrder order, int status) {
		boolean isCancel = false;
		int orderType = order.getType();

		if (status == HeadqInventoryFlowOrder.STATUS_CANCEL)
			isCancel = true;

		String orderId = String.valueOf(order.getId());
		int offset = isCancel ? -1 : 1;
		String orderIdHead = isCancel ? "C" : "";

		if (orderType == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER) { //报损
			orderId = HeadQInventoryStock.INVENTORY_FLOWLOSS + orderIdHead + orderId;
			offset *= -1;
		} else if (orderType == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {//报溢
			orderId = HeadQInventoryStock.INVENTORY_OVERFLOW + orderIdHead + orderId;
		} else if (orderType == HeadqInventoryFlowOrder.INVENTORY_ORDER) {//库房调货
			orderId = HeadQInventoryStock.HEAD_TRANSFER + orderIdHead + orderId;
		} else
			return;

		Iterator<HeadqInventoryFlowOrderProduct> orderProducts = order.getProductSet().iterator();
		while (orderProducts.hasNext()) {
			HeadqInventoryFlowOrderProduct orderProduct = orderProducts.next();

			int quantity = orderProduct.getQuantity() * offset;

			double cost = orderProduct.getCost();

			// 批发价格
			double salePrice = orderProduct.getWholePrice();
			

			//注意：这里的date取的是order_date字段
			HeadQInventoryStock inOutStock = new HeadQInventoryStock(order.getStoreId(),
					orderProduct.getProductBarcode(), orderId, quantity, cost, salePrice, cost * quantity,
					salePrice * quantity,0,order.getOrderDate());
			headQInventoryStockDAOImpl.save(inOutStock, false);
		}
	}

	/**
	 * 初始化搜索库存类单据页面
	 * @param formBean
	 * @param uiBean
	 * @param loginUserInfor
	 */
	public void prepareSearchFlowOrderUI(HeadqInventoryFlowFormBean formBean, HeadqInventoryFlowUIBean uiBean,UserInfor loginUserInfor) {

		uiBean.setInvenOrderTypes(formBean.getFlowOrder().getTypeHQMap());
		uiBean.setInvenOrderStatus(formBean.getFlowOrder().getStatusMap());
		//所有使用中库房
		List<HeadQInventoryStore> stores = headQInventoryStoreDAOImpl.getActiveStores();
		uiBean.setStores(stores);
	}

	/**
	 * function to help search the flow order
	 * 
	 * @param formBean
	 * @param loginUser
	 * @return
	 */
	public Response searchInvenFlowOrders(HeadqInventoryFlowFormBean formBean, Integer page, Integer rowPerPage,
			String sortName, String sortOrder, UserInfor loginUser) {
		Response response = new Response();
		boolean cache = false;

		DetachedCriteria criteria = buildSearchInvenFlowCriter(formBean);
		criteria.setProjection(Projections.rowCount());
		int totalRecord = Common_util.getProjectionSingleValue(headqInventoryFlowOrderDaoImpl.getByCriteriaProjection(criteria, true));

		DetachedCriteria criteria2 = buildSearchInvenFlowCriter(formBean);
		if (sortName.equals("orderDate")) {
			sortName = "orderDate";
		} else if (sortName.equals("typeChainS")) {
			sortName = "type";
		}
		if (sortOrder.equals("asc"))
			criteria2.addOrder(Order.asc(sortName));
		else
			criteria2.addOrder(Order.desc(sortName));

		List<HeadqInventoryFlowOrder> headqOrders = headqInventoryFlowOrderDaoImpl.getByCritera(criteria2,
				Common_util.getFirstRecord(page, rowPerPage), rowPerPage, cache);
		List<HeadqInvenFlowOrderVO> list = new ArrayList<HeadqInvenFlowOrderVO>();

		for (HeadqInventoryFlowOrder order : headqOrders) {

			HeadQInventoryStore store = headQInventoryStoreDAOImpl.get(order.getStoreId(), true);
			UserInfor userInfor = userInforDaoImpl.get(order.getCreator().getUser_id(), true);

			HeadqInvenFlowOrderVO flowOrderVO = new HeadqInvenFlowOrderVO();
			BaseOrder baseOrder = new BaseOrder();

			flowOrderVO.setId(order.getId());
			if(store != null) {
				flowOrderVO.setStoreName(store.getName());
			}			
			flowOrderVO.setCreateByName(userInfor.getName());
			flowOrderVO.setTypeChainS(order.getTypeHQS());
			flowOrderVO.setOrderDate(order.getOrderDate());
			flowOrderVO.setComment(order.getComment());
			flowOrderVO.setStatusS(baseOrder.getStatusMap().get(order.getStatus()));
			flowOrderVO.setStatus(order.getStatus());
			flowOrderVO.setLastUpdateDate(DateUtils.parseDateToStr(order.getLastUpdateDate()));
			flowOrderVO.setLastUpdateBy(order.getLastUpdateBy());

			flowOrderVO.setTotalQuantity(order.getTotalQuantity());
			list.add(flowOrderVO);

			if (order.getType() == HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER) {
				formatTransferOrderComment(order);
				headqInventoryFlowOrderDaoImpl.evict(order);
			}
		}

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("rows", list);
		data.put("total", totalRecord);

		response.setReturnValue(data);

		return response;
	}

	private void formatTransferOrderComment(HeadqInventoryFlowOrder order) {
		HeadQInventoryStore fromChainStore = order.getFromStore();
		HeadQInventoryStore toChainStore = order.getToStore();

		String fromChainName = "非连锁店";
		String toChainName = "非连锁店";

		if (fromChainStore != null && fromChainStore.getId() != 0) {
			fromChainStore = headQInventoryStoreDAOImpl.get(fromChainStore.getId(), true);
			fromChainName = fromChainStore.getName();
			if (fromChainName.length() > 4)
				fromChainName = fromChainName.substring(0, 4);
		}
		if (toChainStore != null && toChainStore.getId() != 0) {
			toChainStore = headQInventoryStoreDAOImpl.get(toChainStore.getId(), true);
			toChainName = toChainStore.getName();
			if (toChainName.length() > 4)
				toChainName = toChainName.substring(0, 4);
		}

		String transferComment = fromChainName + " -> " + toChainName;

		String orderComment = order.getComment();
		if (orderComment.length() > 0)
			order.setComment(transferComment + "<br/>" + orderComment);
		else
			order.setComment(transferComment);

	}

	private DetachedCriteria buildSearchInvenFlowCriter(HeadqInventoryFlowFormBean formBean) {
		DetachedCriteria criteria = DetachedCriteria.forClass(HeadqInventoryFlowOrder.class);

		if (formBean.getFlowOrder().getStoreId() != Common_util.ALL_RECORD) {
			criteria.add(Restrictions.eq("storeId", formBean.getFlowOrder().getStoreId()));
		} 

		if (formBean.getFlowOrder().getStatus() != Common_util.ALL_RECORD)
			criteria.add(Restrictions.eq("status", formBean.getFlowOrder().getStatus()));
		else
			criteria.add(Restrictions.ne("status", HeadqInventoryFlowOrder.STATUS_DELETED));

		int type = formBean.getFlowOrder().getType();
		if (type != Common_util.ALL_RECORD)
			criteria.add(Restrictions.eq("type", type));

		criteria.add(Restrictions.between("orderDate", Common_util.formStartDate(formBean.getSearchStartTime()),Common_util.formEndDate(formBean.getSearchEndTime())));

		return criteria;
	}

	/**
	 * function to prepare the flow order ui bean for display
	 * 
	 * @param loginUser
	 * @param uiBean
	 * @param formBean
	 */
	public void prepareDisplayFlowOrderFormUIBean(UserInfor loginUser, HeadqInventoryFlowUIBean uiBean,
			HeadqInventoryFlowFormBean formBean, HeadqInventoryFlowOrder order) {
		formBean.setFlowOrder(order);
		// 添加仓库信息
		HeadQInventoryStore store = headQInventoryStoreDAOImpl.get(order.getStoreId(), true);
		uiBean.setStoreName(store.getName());
		BaseOrder baseOrder = new BaseOrder();
		uiBean.getFlowOrder().setStatusS(baseOrder.getStatusMap().get(order.getStatus()));
		uiBean.setFlowOrder(order);
	}

	/**
	 * function to create the flow order ui bean for create/edit flow order
	 * 
	 * @param loginUser
	 */
	public void prepareCreateFlowOrderFormUIBean(UserInfor loginUser, HeadqInventoryFlowUIBean uiBean,
			HeadqInventoryFlowFormBean formBean, HeadqInventoryFlowOrder order) {
		formBean.setFlowOrder(order);
		// 1.添加仓库信息
		List<HeadQInventoryStore> stores = headQInventoryStoreDAOImpl.getAll(true);
		uiBean.setStores(stores);
		// 2.添加创建人信息
		formBean.getFlowOrder().setCreator(loginUser);
		// 3. 添加单据日期
		formBean.getFlowOrder().setOrderDate(new Date());
		// 4.添加单据状态
		formBean.getFlowOrder().setStatus(order.getStatus());
		// 5.添加单据状态字符
		formBean.getFlowOrder().setStatusInfo(order.getStatusMaps().get(order.getStatus()));
		// 6.添加调货仓库信息
		List<HeadQInventoryStore> toStores = headQInventoryStoreDAOImpl.getAll(true);
		uiBean.setToStores(toStores);
		//7.添加单据类型
		BaseOrder baseOrder = new BaseOrder();
		formBean.getFlowOrder().setTypeHQS(baseOrder.getTypeHQMap().get(formBean.getFlowOrder().getType()));
		
	}

	@Transactional
	public Response downloadFlowOrder(int id, UserInfor loginUser) throws Exception {
		Response response = new Response();
		List<Object> values = new ArrayList<Object>();

		String webInf = this.getClass().getClassLoader().getResource("").getPath();
		String contextPath = webInf.substring(1, webInf.indexOf("classes")).replaceAll("%20", " ");

		HeadqInventoryFlowOrder order = getOrderById(id, loginUser);

		if (order.getType() == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {
			order.setTypeHQS("总部库存报溢单");
		}
		if (order.getType() == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER) {
			order.setTypeHQS("总部库存报溢单");
		}
		boolean showCost = loginUser.containFunction("purchaseAction!seeCost");

		ByteArrayInputStream byteArrayInputStream;
		HSSFWorkbook wb = null;
		HeadQInventoryStore store = headQInventoryStoreDAOImpl.get(order.getStoreId(), true);
		HeadqInventoryFlowOrderTemplate flowOrderTemplate = new HeadqInventoryFlowOrderTemplate(order, store,contextPath + "template\\", showCost);
		wb = flowOrderTemplate.process();

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		wb.write(os);

		byte[] content = os.toByteArray();
		byteArrayInputStream = new ByteArrayInputStream(content);

		values.add(byteArrayInputStream);
		values.add(order.getTypeHQS());
		response.setReturnValue(values);

		return response;
	}

	/**
	 * the function to delete the order by mark the order status to deleted
	 * 
	 * @param orderId
	 * @param loginUser
	 */
	public Response deleteOrderById(int orderId, UserInfor loginUser) {
		Response response = new Response();
		HeadqInventoryFlowOrder flowOrder = headqInventoryFlowOrderDaoImpl.get(orderId, true);

		if (flowOrder.getStatus() == HeadqInventoryFlowOrder.STATUS_DRAFT) {
			String hql = "UPDATE HeadqInventoryFlowOrder c SET c.status=? WHERE c.id=?";
			Object[] values = new Object[] { HeadqInventoryFlowOrder.STATUS_DELETED, orderId };

			int count = headqInventoryFlowOrderDaoImpl.executeHQLUpdateDelete(hql, values, true);

			if (count == 0) {
				response.setReturnCode(Response.FAIL);
				response.setMessage("删除单据失败");
			} else {
				response.setReturnCode(Response.SUCCESS);
				response.setMessage("成功删除单据");
			}
		} else {
			response.setReturnCode(Response.FAIL);
			response.setMessage("过账的单据无法删除");
		}

		return response;
	}

	/**
	 * function to prepare the flow order ui bean for search
	 * 
	 * @param loginUser
	 * @param uiBean
	 * @param formBean
	 */
	public void prepareSearchFlowOrderFormUIBean(UserInfor loginUser, HeadqInventoryFlowUIBean uiBean,
			HeadqInventoryFlowFormBean formBean) {
		// 1. set the store list

		// 2. set the status
		HeadqInventoryFlowOrder headqInventoryFlowOrder = new HeadqInventoryFlowOrder();
		uiBean.setInvenOrderStatus(headqInventoryFlowOrder.getStatusMap());

		// 3. set the type
		uiBean.setInvenOrderTypes(formBean.getFlowOrder().getTypeChainMap());

	}

	/**
	 * function to cancel the flow order 红冲
	 */
	@Transactional
	public Response cancelOrder(int orderId, UserInfor loginUser) {
		HeadqInventoryFlowOrder flowOrder = getOrderById(orderId, loginUser);
		int status_org = flowOrder.getStatus();
		Response response = new Response();
		if (status_org == HeadqInventoryFlowOrder.STATUS_COMPLETE) {
			// 1. 红冲单据，修改状态
			String hql = "UPDATE HeadqInventoryFlowOrder c SET c.status=? WHERE c.id=?";
			Object[] values = new Object[] { ChainInventoryFlowOrder.STATUS_CANCEL, orderId };

			int count = headqInventoryFlowOrderDaoImpl.executeHQLUpdateDelete(hql, values, true);

			if (count == 0) {
				response.setReturnCode(Response.FAIL);
				response.setMessage("红冲单据失败");
			} else {
				// 2. 修改stock in/out table
				// 只有报溢单,报损单，调货单可以
				if (flowOrder.getType() == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER
						|| flowOrder.getType() == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {
					updateHeadqFlowOrderInOutStock(flowOrder, ChainStoreSalesOrder.STATUS_CANCEL);

				} else if (flowOrder.getType() == ChainInventoryFlowOrder.INVENTORY_TRANSFER_ORDER) {
					// 调货单红冲
					updateHeadqInvenTransferInOutStock(flowOrder, ChainStoreSalesOrder.STATUS_CANCEL);
				}

				response.setReturnCode(Response.SUCCESS);
				response.setMessage("成功红冲单据");
			}
		} else {
			response.setReturnCode(Response.FAIL);
			response.setMessage("只有过账的单据可以红冲");
		}

		return response;
	}

	/**
	 * 获取总部所有仓库信息
	 * 
	 * @return
	 */
	public void initInventoryTracking(HeadqInventoryFlowUIBean uiBean) {
		List<HeadQInventoryStore> headStores = headQInventoryStoreDAOImpl.getAll(true);
		headStores.add(0, HeadQInventoryStoreDAOImpl.getDummyAllStore());
		uiBean.setStores(headStores);
		uiBean.setBelongMap(Common_util.getBelongMap());
		
	}
	
	
	/**
	 * 获取总部所有仓库信息
	 * 
	 * @return
	 */
	public Response getHqInventoryStores() {
		Response response = new Response();
		List<HeadQInventoryStore> headStores = headQInventoryStoreDAOImpl.getActiveStores();

		response.setReturnValue(headStores);
		response.setReturnCode(Response.SUCCESS);
		return response;
	}
	
	/**
	 * 获取所有库房信息
	 * @return
	 */
	public List<HeadQInventoryStore> getHqAllStore() {
		List<HeadQInventoryStore> headStores = headQInventoryStoreDAOImpl.getActiveStores();
		return headStores;
	}
	

	public void prepareGetStoreInventoryRpt(HeadqInventoryFlowFormBean formBean, HeadqInventoryFlowUIBean uiBean) {
// 未使用多选库房之前逻辑
//		if (formBean.getStoreId() == Common_util.ALL_RECORD)
//			uiBean.setStoreName("所有仓库");
//		else {
//			HeadQInventoryStore store = headQInventoryStoreDAOImpl.get(formBean.getStoreId(), true);
//			uiBean.setStoreName(store.getName());
//		}
		
		String storeName = "";
		if (StringUtils.isNotBlank(formBean.getStoreIds())) {
			String[] ids = formBean.getStoreIds().split(",");
			for (int i = 0; i < ids.length; i++) {
				HeadQInventoryStore store  = headQInventoryStoreDAOImpl.get(Integer.valueOf(ids[i].trim()), true);
				if (store != null) {
					storeName += store.getName() + ",";
				}
			}
		}else {
			storeName = "所有库房";
		}
		
		uiBean.setStoreName(storeName);
		uiBean.setStoreIds(formBean.getStoreIds());
		int belongTo = formBean.getBelongTo();
		uiBean.setBelongToS(Common_util.getBelongMap().get(belongTo));

	}

	/**
	 * function to group the flow order's product list 1. 对产品分组按照条码 2. 获取inventory
	 * level
	 * 
	 * @param flowOrder
	 * @throws Exception
	 */
	private void groupProductList(HeadqInventoryFlowOrder flowOrder) {
		List<HeadqInventoryFlowOrderProduct> productList = flowOrder.getProductList();

		// to store the sequence product id list
		Set<String> barcodes = new LinkedHashSet<String>();
		Set<Integer> pbIds = new LinkedHashSet<Integer>();

		// list of the post-group
		List<HeadqInventoryFlowOrderProduct> productList2 = new ArrayList<HeadqInventoryFlowOrderProduct>();

		// 1. to group the quantity
		Map<String, HeadqInventoryFlowOrderProduct> productMap = new HashMap<String, HeadqInventoryFlowOrderProduct>();
		int totalProductQ = 0;
		int totalInventoryLevel = 0;
		for (HeadqInventoryFlowOrderProduct orderProduct : productList) {
			if (orderProduct != null) {
				ProductBarcode productBarcode = orderProduct.getProductBarcode();
				if (productBarcode != null) {
					String barcode = productBarcode.getBarcode();
					int productId = productBarcode.getId();
					if (barcode != null && !barcode.equals("") && productId != 0) {
						// 1.1 to make the order product ids
						barcodes.add(barcode);
						pbIds.add(productId);

						// 1.2 to group the product quantity
						int productQ = orderProduct.getQuantity();
						totalProductQ += productQ;
						HeadqInventoryFlowOrderProduct orderProduct2 = productMap.get(barcode);

						if (orderProduct2 != null) {
							int originalQ = orderProduct2.getQuantity();
							orderProduct2.setQuantity(productQ + originalQ);
						} else {
							productMap.put(barcode, orderProduct);
						}
					}
				}
			}
		}
		flowOrder.setTotalQuantity(totalProductQ);

		// 2. calculate the inventory if it is inventory order
		if (flowOrder.getType() == HeadqInventoryFlowOrder.INVENTORY_ORDER) {
			HeadQInventoryStore store = headQInventoryStoreDAOImpl.get(flowOrder.getStoreId(), true);
			Map<String, Integer> inventoryLevelMap = this.getProductsInventoryLevel(pbIds, store.getId());

			// 2.2 to make the new list with inventory level map
			for (String barcode : barcodes) {
				HeadqInventoryFlowOrderProduct orderProduct = productMap.get(barcode);
				Integer inventoryLevel = inventoryLevelMap.get(barcode);
				int inventoryLevel_int = 0;

				if (inventoryLevel != null)
					inventoryLevel_int = inventoryLevel.intValue();

				totalInventoryLevel += inventoryLevel_int;

				if (orderProduct == null) {
					loggerLocal.error("在汇总数据时发生错误");
				} else {
					orderProduct.setInventoryQ(inventoryLevel_int);
					orderProduct.setQuantityDiff(orderProduct.getQuantity() - inventoryLevel_int);
					productList2.add(orderProduct);
				}

			}
			flowOrder.setTotalQuantityDiff(totalProductQ - totalInventoryLevel);
			flowOrder.setTotalInventoryQ(totalInventoryLevel);
		} else {
			// 2.2 to make the new list
			for (String barcode : barcodes) {
				HeadqInventoryFlowOrderProduct orderProduct = productMap.get(barcode);
				if (orderProduct == null) {
					loggerLocal.error("在汇总数据时发生错误");
				} else {
					productList2.add(orderProduct);
				}
			}
		}

		// 3. set the new list
		flowOrder.setProductList(productList2);

	}

	/**
	 * key: 条码 value: 数量
	 * 
	 * @param pbIds
	 * @param storeId
	 * @return
	 */
	public Map<String, Integer> getProductsInventoryLevel(Set<Integer> pbIds, int storeId) {
		Map<Integer, Integer> inventoryFlowMap = new HashMap<Integer, Integer>();

		if (pbIds != null && pbIds.size() > 0) {
			inventoryFlowMap = headQInventoryStockDAOImpl.getProductsInventoryLevel(pbIds, storeId);
		}
//		
//		Map<String, Integer> initialInventoryMap = chainInitialStockDaoImpl.getProductsInventoryLevel(barcodes, clientId);

		Map<String, Integer> stockMap = new HashMap<String, Integer>();

		for (Integer pbId : inventoryFlowMap.keySet()) {
			ProductBarcode pbBarcode = productBarcodeDaoImpl.get(pbId, true);

			stockMap.put(pbBarcode.getBarcode(), inventoryFlowMap.get(pbId));
		}

		return stockMap;

	}

	/**
	 * 调库产生的库存需要修改
	 * 
	 * @param order
	 * @param status
	 */
	private void updateHeadqInvenTransferInOutStock(HeadqInventoryFlowOrder order, int status) {
		boolean isCancel = false;
		HeadQInventoryStore fromChainStore = order.getFromStore();
		HeadQInventoryStore toChainStore = order.getToStore();

		int fromClientId = fromChainStore.getId();
		int toClientId = toChainStore.getId();

		if (fromClientId == 0 && toClientId == 0)
			loggerLocal.error("调货单据的调出仓库和调入仓库不能同时为空. 单据号" + order.getId());

		if (status == HeadqInventoryFlowOrder.STATUS_CANCEL)
			isCancel = true;

		String orderId = String.valueOf(order.getId());
		int offset = isCancel ? -1 : 1;
		String orderIdHead = isCancel ? "C" : "";

		orderId = HeadQInventoryStock.HEAD_TRANSFER + orderIdHead + orderId;

		Iterator<HeadqInventoryFlowOrderProduct> orderProducts = order.getProductSet().iterator();
		while (orderProducts.hasNext()) {
			HeadqInventoryFlowOrderProduct orderProduct = orderProducts.next();

			int quantity = orderProduct.getQuantity() * offset;

			/**
			 * 1. 为from chain准备库存调出
			 */
			double salePrice = orderProduct.getWholePrice();
			double cost = orderProduct.getCost();

			if (fromClientId > 0) {
				// to get the latest cost for from wholesaler
				int fromQuantity = -1 * quantity;

				HeadQInventoryStock inOutStock = new HeadQInventoryStock(fromClientId, orderProduct.getProductBarcode(),
						orderId, quantity * -1, cost, salePrice, cost * fromQuantity, salePrice * fromQuantity,0,order.getOrderDate());
				headQInventoryStockDAOImpl.save(inOutStock, false);
			}

			/**
			 * 为to chain store准备库存调入单, 和saleshistory
			 */
			if (toClientId > 0) {
				// 1. 更新in-out
				HeadQInventoryStock inOutStock = new HeadQInventoryStock(toClientId, orderProduct.getProductBarcode(),
						orderId, quantity, cost, salePrice, cost * quantity, salePrice * quantity,0,order.getOrderDate());
				headQInventoryStockDAOImpl.save(inOutStock, false);
			}
		}
	}

	/**
	 * 准备调货单的页面内容
	 * 
	 * @param loginUser
	 * @param uiBean
	 * @param formBean
	 * @param order
	 */
	@Transactional
	public void prepareCreateInvenTransferOrderFormUIBean(UserInfor loginUser, HeadqInventoryFlowUIBean uiBean,
			HeadqInventoryFlowFormBean formBean, HeadqInventoryFlowOrder order) {
		formBean.setFlowOrder(order);

		// 添加仓库信息
		List<HeadQInventoryStore> stores = headQInventoryStoreDAOImpl.getActiveStores();
		uiBean.setStores(stores);

		// 2. set the creator
		formBean.getFlowOrder().setCreator(loginUser);

		// 3. set the date
		formBean.getFlowOrder().setOrderDate(new Date());

		// 添加调货仓库信息
		List<HeadQInventoryStore> toStores = headQInventoryStoreDAOImpl.getActiveStores();
		uiBean.setToStores(toStores);

		uiBean.setToStores(toStores);

	}

	/**
	 * 保存 库存盘点单据
	 * 
	 * @param flowOrder
	 * @param loginUser
	 * @throws Exception
	 */
	@Transactional
	public Response saveInventoryToDraft(HeadqInventoryFlowOrder flowOrder, File file, UserInfor loginUser,String jsons)throws Exception {
		Response response = new Response();
		//填充:将json字符串转对象集合
		fillFlowOrder(flowOrder, jsons);
		//校验货品是否归属该库房
		response =  isCheckProduct(flowOrder);
		if (response.getReturnCode() == Response.FAIL) {
			flowOrder.setStatus(HeadqInventoryFlowOrder.STATUS_DRAFT);
			save(flowOrder, loginUser);
			return response;
		}
		int status_org = flowOrder.getStatus();
		if (status_org == HeadqInventoryFlowOrder.STATUS_INITIAL || status_org == HeadqInventoryFlowOrder.STATUS_DRAFT) {
			flowOrder.setStatus(HeadqInventoryFlowOrder.STATUS_DRAFT);

			List<HeadqInventoryFlowOrderProduct> products = null;
			boolean isFileError = false;
			try {
				products = parseInventoryFile(file, flowOrder.getStoreId());
			} catch (Exception e) {
				response.setQuickValue(Response.FAIL, "库存文件格式错误");
				isFileError = true;				
			}

			List<HeadqInventoryFlowOrderProduct> currentProducts = flowOrder.getProductList();
			
			if (isFileError) {
				save(flowOrder, loginUser);
				response.setFail("经扫描的条码信息已存入草稿，而附带上传的文件存在文件格式错误，所以文件条码信息未录入草稿单据");	
			}else {
				currentProducts.addAll(products);
				save(flowOrder, loginUser);
				response.setQuickValue(Response.SUCCESS, "已经成功保存");				
			}			
			response.setReturnValue(flowOrder.getId());			
		} else {
			response.setQuickValue(Response.FAIL, "保存草稿失败");
		}

		return response;

	}
	
	
	/**
	 * 保存 库存盘点单据
	 * 
	 * @param flowOrder
	 * @param loginUser
	 * @throws Exception
	 */
	@Transactional
	public Response refreshInventoryOrder(HeadqInventoryFlowOrder flowOrder,  UserInfor loginUser,String jsons)throws Exception {
		Response response = new Response();
		//填充:将json字符串转对象集合
		fillFlowOrder(flowOrder, jsons);
		int status_org = flowOrder.getStatus();
		if (status_org == HeadqInventoryFlowOrder.STATUS_INITIAL || status_org == HeadqInventoryFlowOrder.STATUS_DRAFT) {
			flowOrder.setStatus(HeadqInventoryFlowOrder.STATUS_DRAFT);
			
			save(flowOrder, loginUser);
			response.setQuickValue(Response.SUCCESS, "刷新完成");										
			response.setReturnValue(flowOrder.getId());			
		} else {
			response.setQuickValue(Response.FAIL, "刷新失败");
		}

		return response;

	}

	/**
	 * the function to calculate the inventory order
	 * 
	 * @param flowOrder
	 * @return
	 */
	public Response calculateInventoryOrder(HeadqInventoryFlowOrder flowOrder) {
		Response response = new Response();

		int orderId = flowOrder.getId();

		groupProductList(flowOrder);

		if (orderId != 0) {
			HeadqInventoryFlowOrder inventoryFlowOrder = headqInventoryFlowOrderDaoImpl.get(orderId, true);
			if (inventoryFlowOrder != null) {
				inventoryFlowOrder.setProductList(flowOrder.getProductList());
				inventoryFlowOrder.setTotalInventoryQ(flowOrder.getTotalInventoryQ());
				inventoryFlowOrder.setTotalQuantity(flowOrder.getTotalQuantity());
				inventoryFlowOrder.setTotalQuantityDiff(flowOrder.getTotalQuantityDiff());

				response.setReturnCode(Response.SUCCESS);
				response.setReturnValue(inventoryFlowOrder);

				return response;
			} else {
				response.setReturnCode(Response.FAIL);
				response.setMessage("重新计算失败:原始单据无法找到");
				return response;
			}
		} else {
			response.setReturnCode(Response.SUCCESS);
			response.setReturnValue(flowOrder);
			return response;
		}
	}



	/**
	 * 自动纠正库存
	 * 
	 * @param flowOrder
	 * @param loginUser
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public Response adjustInventory(HeadqInventoryFlowOrder inventoryOrder, UserInfor loginUser,String jsons) throws Exception {

		Response response = new Response();
		//填充:将json字符串转对象集合
		fillFlowOrder(inventoryOrder, jsons);
		//校验货品是否归属该库房
		response =  isCheckProduct(inventoryOrder);
		if (response.getReturnCode() == Response.FAIL) {
			inventoryOrder.setStatus(inventoryOrder.STATUS_DRAFT);
			save(inventoryOrder, loginUser);
			return response;
		}

		if (inventoryOrder.getId() == Common_util.ALL_RECORD_NEW || inventoryOrder.getStatus() == inventoryOrder.STATUS_DRAFT) {
			inventoryOrder.setStatus(HeadqInventoryFlowOrder.STATUS_COMPLETE);

			// 1.整理order product
			groupProductList(inventoryOrder);

			// 2. 自动创建报损单，报溢单
			// 报溢单
			HeadqInventoryFlowOrder overFlowOrder = new HeadqInventoryFlowOrder();

			// 报损单
			HeadqInventoryFlowOrder flowLossOrder = new HeadqInventoryFlowOrder();

			List<HeadqInventoryFlowOrderProduct> overFlowOrderProducts = new ArrayList<HeadqInventoryFlowOrderProduct>();
			List<HeadqInventoryFlowOrderProduct> flowLossOrderProducts = new ArrayList<HeadqInventoryFlowOrderProduct>();
			List<HeadqInventoryFlowOrderProduct> inventoryOrderProducts = inventoryOrder.getProductList();
			int totalInventoryQ_overFlow = 0;
			int totalQuantity_overFlow = 0;
			int totalInventoryQ_flowLoss = 0;
			int totalQuantity_flowLoss = 0;
			for (HeadqInventoryFlowOrderProduct inventoryOrderProduct : inventoryOrderProducts) {
				int quantityDiff = inventoryOrderProduct.getQuantityDiff();
				int inventoryQ = inventoryOrderProduct.getInventoryQ();
				ProductBarcode productBarcode = inventoryOrderProduct.getProductBarcode();

				// 实际库存 > 电脑库存
				if (quantityDiff > 0) {
					HeadqInventoryFlowOrderProduct overFlowOrderProduct = new HeadqInventoryFlowOrderProduct();
					overFlowOrderProduct.setInventoryQ(inventoryQ);
					overFlowOrderProduct.setQuantity(quantityDiff);
					overFlowOrderProduct.setProductBarcode(productBarcode);
					overFlowOrderProduct.setComment("一键纠正");
					overFlowOrderProducts.add(overFlowOrderProduct);
					totalInventoryQ_overFlow += inventoryQ;
					totalQuantity_overFlow += quantityDiff;
					// 实际库存 < 电脑库存
				} else if (quantityDiff < 0) {
					HeadqInventoryFlowOrderProduct flowLossOrderProduct = new HeadqInventoryFlowOrderProduct();
					flowLossOrderProduct.setInventoryQ(inventoryQ);
					flowLossOrderProduct.setQuantity(Math.abs(quantityDiff));
					flowLossOrderProduct.setProductBarcode(productBarcode);
					flowLossOrderProduct.setComment("一键纠正");
					flowLossOrderProducts.add(flowLossOrderProduct);
					totalInventoryQ_flowLoss += inventoryQ;
					totalQuantity_flowLoss += Math.abs(quantityDiff);
				}
			}
			String msg = "";
			if (overFlowOrderProducts.size() > 0) {
				overFlowOrder.setStoreId(inventoryOrder.getStoreId());
				overFlowOrder.setCreator(loginUser);
				overFlowOrder.setOrderDate(new Date());
				overFlowOrder.setStatus(HeadqInventoryFlowOrder.STATUS_INITIAL);
				overFlowOrder.setType(HeadqInventoryFlowOrder.OVER_FLOW_ORDER);
				overFlowOrder.setTotalInventoryQ(totalInventoryQ_overFlow);
				overFlowOrder.setTotalQuantity(totalQuantity_overFlow);
				overFlowOrder.setComment("一键纠正" + inventoryOrder.getId());
				overFlowOrder.setProductList(overFlowOrderProducts);
				overFlowOrder.buildIndex();
				overFlowOrder.putListToSet();
				saveToFinal(overFlowOrder, loginUser);
				msg += "报溢单据号:" + overFlowOrder.getId() + "\n";
			}
			if (flowLossOrderProducts.size() > 0) {
				flowLossOrder.setStoreId(inventoryOrder.getStoreId());
				flowLossOrder.setCreator(loginUser);
				flowLossOrder.setOrderDate(new Date());
				flowLossOrder.setStatus(HeadqInventoryFlowOrder.STATUS_INITIAL);
				flowLossOrder.setType(HeadqInventoryFlowOrder.FLOW_LOSS_ORDER);
				flowLossOrder.setTotalInventoryQ(totalInventoryQ_flowLoss);
				flowLossOrder.setTotalQuantity(totalQuantity_flowLoss);
				flowLossOrder.setComment("一键纠正" + inventoryOrder.getId());
				flowLossOrder.setProductList(flowLossOrderProducts);
				flowLossOrder.buildIndex();
				flowLossOrder.putListToSet();
				saveToFinal(flowLossOrder, loginUser);
				msg += "报损单据号:" + flowLossOrder.getId() + "\n";
			}

			response.setReturnCode(Response.SUCCESS);
			if (msg.length() > 0)
				response.setMessage("已经成功自动生成." + msg);
			else
				response.setMessage("所有实际库存和电脑库存都匹配.无需纠正库存");
		} else {
			response.setReturnCode(Response.FAIL);
			response.setMessage("生成报表或者红冲的单据不能再做一键纠正");
		}

		return response;
	}

	/**
	 * 将会按照这张单据成为实际库存
	 * 
	 * @param flowOrder
	 * @param loginUser
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public Response clearAndadjustInventory(HeadqInventoryFlowOrder inventoryOrder, UserInfor loginUser,String jsons)
			throws Exception {

		Response response = new Response();
		//填充:将json字符串转对象集合
		fillFlowOrder(inventoryOrder, jsons);
		//校验货品是否归属该库房
		response =  isCheckProduct(inventoryOrder);
		if (response.getReturnCode() == Response.FAIL) {
			inventoryOrder.setStatus(inventoryOrder.STATUS_DRAFT);
			save(inventoryOrder, loginUser);
			return response;
		}
		if (inventoryOrder.getId() == Common_util.ALL_RECORD_NEW  || inventoryOrder.getStatus() == inventoryOrder.STATUS_DRAFT) {
			// 1.整理这张单据中order product
			List<HeadqInventoryFlowOrderProduct> productList = inventoryOrder.getProductList();
			// to store the sequence product id list
			Set<String> barcodeInOrder = new LinkedHashSet<String>();
			Map<String, Integer> inventoryInOrderMap = new HashMap<String, Integer>();
			for (HeadqInventoryFlowOrderProduct orderProduct : productList) {
				if (orderProduct != null) {
					ProductBarcode productBarcode = orderProduct.getProductBarcode();
					if (productBarcode != null) {
						String barcode = productBarcode.getBarcode();
						int productId = productBarcode.getId();
						if (barcode != null && !barcode.equals("") && productId != 0) {
							// 1.1 to make the order product ids
							barcodeInOrder.add(barcode);

							// 1.2 to group the product quantity
							int productQ = orderProduct.getQuantity();
							Integer inventoryObj = inventoryInOrderMap.get(barcode);

							if (inventoryObj != null) {
								inventoryInOrderMap.put(barcode, productQ + inventoryObj);
							} else {
								inventoryInOrderMap.put(barcode, productQ);
							}
						}
					}
				}
			}

			// 1.2 把这次年份和季度整理出来
			List<String> yearQuarterNames = new ArrayList<String>();
			getYearQuarterInOrder(inventoryOrder, yearQuarterNames,jsons);
			Map<String, Year> yearMap = yearDaoImpl.getYearNameMap();
			Map<String, Quarter> quarterMap = quarterDaoImpl.getQuarterNameMap();

			// 2. 获取出连锁店目前电脑存在的库存,只包含在year quarterkey里面
			Map<String, Integer> inventoryPCMap = new HashMap<String, Integer>();

			String hqlString = "SELECT i.productBarcode.id, SUM(i.quantity) FROM HeadQInventoryStock i JOIN i.productBarcode pb JOIN pb.product p  ";//

			// 做sql 拼接
			String hqlWhere = "WHERE i.storeId = " + inventoryOrder.getStoreId() + " and p.year.year_ID in ( ";
			String yearWhere = "";
			String quarterWhere = "";
			if (yearQuarterNames != null && !yearQuarterNames.isEmpty()) {

				String[] keyArray = yearQuarterNames.get(0).split("-");

				int yearKey = yearMap.get(keyArray[0]).getYear_ID();
				int quarterKey = quarterMap.get(keyArray[1]).getQuarter_ID();
				yearWhere = "" + yearKey;
				quarterWhere = "" + quarterKey;

				for (int i = 1; i < yearQuarterNames.size(); i++) {
					keyArray = yearQuarterNames.get(i).split("-");
					yearKey = yearMap.get(keyArray[0]).getYear_ID();
					quarterKey = quarterMap.get(keyArray[1]).getQuarter_ID();

					yearWhere += "," + yearKey;

					quarterWhere += "," + quarterKey;
				}
				yearWhere += ")and p.quarter.quarter_ID in (";

				hqlWhere += yearWhere;

				quarterWhere += ")";
				hqlWhere += quarterWhere;

				String sqlEnd = "GROUP BY i.productBarcode.id";

				loggerLocal.info(hqlString + hqlWhere);

				List<HeadQInventoryStock> result = headQInventoryStockDAOImpl.getByHQL(hqlString + hqlWhere + sqlEnd,
						null, true);
				for (int i = 0; i < result.size(); i++) {
					Object object = result.get(i);
					if (object != null) {
						Object[] recordResult = (Object[]) object;
						int pbId = Common_util.getInt(recordResult[0]);
						int quantity = Common_util.getInt(recordResult[1]);
						ProductBarcode pb = productBarcodeDaoImpl.get(pbId, true);
						inventoryPCMap.put(pb.getBarcode(), quantity);
					}
				}
				Set<String> barcodeInPC = new HashSet<String>();
				barcodeInPC = inventoryPCMap.keySet();

				Set<String> barcodeAll = new HashSet<String>();
				barcodeAll.addAll(barcodeInOrder);
				barcodeAll.addAll(barcodeInPC);

				// 3. 获取productbarcode 对象
				Map<String, ProductBarcode> barcodeMap = productBarcodeDaoImpl.getProductMapByBarcode(barcodeAll);

				// 3. 自动创建报损单，报溢单
				HeadqInventoryFlowOrder overFlowOrder = new HeadqInventoryFlowOrder();
				HeadqInventoryFlowOrder flowLossOrder = new HeadqInventoryFlowOrder();
				List<HeadqInventoryFlowOrderProduct> overFlowOrderProducts = new ArrayList<HeadqInventoryFlowOrderProduct>();
				List<HeadqInventoryFlowOrderProduct> flowLossOrderProducts = new ArrayList<HeadqInventoryFlowOrderProduct>();

				int totalInventoryQ_overFlow = 0;
				int totalQuantity_overFlow = 0;
				int totalInventoryQ_flowLoss = 0;
				int totalQuantity_flowLoss = 0;
				for (String barcode : barcodeAll) {
					Integer quantityInOrderObj = inventoryInOrderMap.get(barcode);
					Integer quantityInPCObj = inventoryPCMap.get(barcode);

					if (quantityInOrderObj == null && quantityInPCObj == null)
						continue;

					int quantityInOrder = quantityInOrderObj == null ? 0 : quantityInOrderObj.intValue();
					int quantityInPC = quantityInPCObj == null ? 0 : quantityInPCObj.intValue();

					int quantityDiff = quantityInOrder - quantityInPC;
					ProductBarcode productBarcode = barcodeMap.get(barcode);
					if (productBarcode == null) {
						loggerLocal.error("保存库存单据错误 : " + barcode);
						continue;
					}

					// 实际库存 > 电脑库存
					if (quantityDiff > 0) {
						HeadqInventoryFlowOrderProduct overFlowOrderProduct = new HeadqInventoryFlowOrderProduct();
						overFlowOrderProduct.setInventoryQ(quantityInPC);
						overFlowOrderProduct.setQuantity(quantityDiff);
						overFlowOrderProduct.setProductBarcode(productBarcode);
						overFlowOrderProduct.setComment("库存扎帐");
						overFlowOrderProducts.add(overFlowOrderProduct);
						totalInventoryQ_overFlow += quantityInPC;
						totalQuantity_overFlow += quantityDiff;
						// 实际库存 < 电脑库存
					} else if (quantityDiff < 0) {
						HeadqInventoryFlowOrderProduct flowLossOrderProduct = new HeadqInventoryFlowOrderProduct();
						flowLossOrderProduct.setInventoryQ(quantityInPC);
						flowLossOrderProduct.setQuantity(Math.abs(quantityDiff));
						flowLossOrderProduct.setProductBarcode(productBarcode);
						flowLossOrderProduct.setComment("库存扎帐");
						flowLossOrderProducts.add(flowLossOrderProduct);
						totalInventoryQ_flowLoss += quantityInPC;
						totalQuantity_flowLoss += Math.abs(quantityDiff);
					}
				}

				String msg = "";
				if (overFlowOrderProducts.size() > 0) {
					overFlowOrder.setStoreId(inventoryOrder.getStoreId());
					overFlowOrder.setCreator(loginUser);
					overFlowOrder.setOrderDate(new Date());
					overFlowOrder.setStatus(ChainInventoryFlowOrder.STATUS_INITIAL);
					overFlowOrder.setType(ChainInventoryFlowOrder.OVER_FLOW_ORDER);
					overFlowOrder.setTotalInventoryQ(totalInventoryQ_overFlow);
					overFlowOrder.setTotalQuantity(totalQuantity_overFlow);
					overFlowOrder.setComment("库存扎帐" + inventoryOrder.getId());
					overFlowOrder.setProductList(overFlowOrderProducts);
					overFlowOrder.buildIndex();
					overFlowOrder.putListToSet();
					saveToFinal(overFlowOrder, loginUser);
					msg += "报溢单据号:" + overFlowOrder.getId() + "\n";
				}
				if (flowLossOrderProducts.size() > 0) {
					flowLossOrder.setStoreId(inventoryOrder.getStoreId());
					flowLossOrder.setCreator(loginUser);
					flowLossOrder.setOrderDate(new Date());
					flowLossOrder.setStatus(HeadqInventoryFlowOrder.STATUS_INITIAL);
					flowLossOrder.setType(HeadqInventoryFlowOrder.FLOW_LOSS_ORDER);
					flowLossOrder.setTotalInventoryQ(totalInventoryQ_flowLoss);
					flowLossOrder.setTotalQuantity(totalQuantity_flowLoss);
					flowLossOrder.setComment("库存扎帐" + inventoryOrder.getId());
					flowLossOrder.setProductList(flowLossOrderProducts);
					flowLossOrder.buildIndex();
					flowLossOrder.putListToSet();
					saveToFinal(flowLossOrder, loginUser);
					msg += "报损单据号:" + flowLossOrder.getId() + "\n";
				}

				response.setReturnCode(Response.SUCCESS);
				if (msg.length() > 0)
					response.setMessage("已经将电脑库存清空并修正成实际库存。成功自动生成." + msg);
				else
					response.setMessage("所有实际库存和电脑库存都匹配.无需纠正库存");
			} else {
				response.setReturnCode(Response.FAIL);
				response.setMessage("生成报表或者红冲的单据不能再做一键纠正");
			}

		}
		return response;
	}

	/**
	 * 获取这个盘点单中所有的年份和季度
	 * 
	 * @param inventoryOrder
	 * @return
	 */
	public Response getYearQuarterInOrder(HeadqInventoryFlowOrder inventoryOrder, List<String> yearQuarterKey,String jsons) {
		//填充:将json字符串转对象集合
		fillFlowOrder(inventoryOrder, jsons);
		List<HeadqInventoryFlowOrderProduct> productList = inventoryOrder.getProductList();
		Set<String> yearQuarter = new HashSet<String>();
		Product product = null;
		for (HeadqInventoryFlowOrderProduct orderProduct : productList) {
			if (orderProduct == null || orderProduct.getProductBarcode() == null
					|| orderProduct.getProductBarcode().getId() == 0
					|| orderProduct.getProductBarcode().getBarcode() == "")
				continue;
			product = orderProduct.getProductBarcode().getProduct();
			yearQuarter.add(product.getYear().getYear() + "-" + product.getQuarter().getQuarter_Name());
			String key = product.getYear().getYear() + "-" + product.getQuarter().getQuarter_Name();
			if (yearQuarterKey != null && !yearQuarterKey.contains(key))
				yearQuarterKey.add(key);
		}

		List<String> yearQuarterList = new ArrayList<String>(yearQuarter);
		Collections.sort(yearQuarterList);

		Response response = new Response();
		response.setReturnCode(Response.SUCCESS);
		response.setReturnValue(yearQuarterList);
		return response;
	}

	/**
	 * function to generatet the inventory report
	 * 
	 * @param flowOrder
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public Response genInventoryReport(HeadqInventoryFlowOrder flowOrder, File file, String jsons,UserInfor loginUser)
			throws Exception {
		int status_org = flowOrder.getStatus();
		Response response = new Response();
		//填充:将json字符串转对象集合
		fillFlowOrder(flowOrder, jsons);
		//校验货品是否归属该库房
		response =  isCheckProduct(flowOrder);
		if (response.getReturnCode() == Response.FAIL) {
			flowOrder.setStatus(flowOrder.STATUS_DRAFT);
			save(flowOrder, loginUser);
			return response;
		}
		if (status_org == HeadqInventoryFlowOrder.STATUS_INITIAL
				|| status_org == HeadqInventoryFlowOrder.STATUS_DRAFT) {
			

			List<HeadqInventoryFlowOrderProduct> products = null;
			boolean isFileError = false;
			try {
				products = parseInventoryFile(file, flowOrder.getStoreId());
			} catch (Exception e) {
				response.setQuickValue(Response.FAIL, "库存文件格式错误");
				isFileError = true;
			}

			List<HeadqInventoryFlowOrderProduct> currentProducts = flowOrder.getProductList();
			
			if (isFileError) {
				flowOrder.setStatus(HeadqInventoryFlowOrder.STATUS_DRAFT);
				headqInventoryFlowOrderDaoImpl.initialize(flowOrder.getProductList());
				save(flowOrder, loginUser);
				response.setQuickValue(Response.FAIL,"经扫描的条码信息已存入草稿，而附带上传的文件存在文件格式错误，所以文件条码信息未录入草稿单据");	
			}else {
				flowOrder.setStatus(HeadqInventoryFlowOrder.STATUS_COMPLETE);
				currentProducts.addAll(products);
				headqInventoryFlowOrderDaoImpl.initialize(flowOrder.getProductList());
				save(flowOrder, loginUser);
				response.setQuickValue(Response.SUCCESS, "已经成功保存");				
			}

		} else {
			response.setReturnCode(Response.FAIL);
			response.setMessage("保存单据失败");
		}

		return response;
	}

	/**
	 * 获取条形码，然后生成一个inputsteam
	 * 
	 * @return
	 */
	public InputStream genBarcodeFile() {
		// 1. 准备前四年的年份
		Date today = new Date();
		int thisYear = 1900 + today.getYear();

		// 2. 新增一年
		//thisYear++;

		List<String> years = new ArrayList<String>();
		for (int i = 0; i < 4; i++)
			years.add(String.valueOf(thisYear - i));

		// 2. 获取前四年的year
		List<Year> years2 = yearDaoImpl.getYear(years);

		List<ProductBarcode> productBarcodes = productBarcodeDaoImpl.getBarcodeByYear(years2);
		StringBuffer barcodeBuffer = new StringBuffer();

		String barcode = "";
		String productCode = "";
		String brandName = "";
		Color color = null;
		String colorName = "";
		for (ProductBarcode productBarcode : productBarcodes) {
			barcode = productBarcode.getBarcode();
			productCode = productBarcode.getProduct().getProductCode();
			brandName = productBarcode.getProduct().getBrand().getBrand_Name();
			color = productBarcode.getColor();
			if (color != null)
				colorName = color.getName();

			barcodeBuffer.append(barcode + "," + productCode + "," + brandName + "," + colorName + "," + "\n");
			// barcodeBuffer.append(productBarcode.getId() + ",1"+ "\n" );
		}

		ByteArrayInputStream is = new ByteArrayInputStream(barcodeBuffer.toString().getBytes());
		return is;
	}

	/**
	 * to parse the file from the inventory machine
	 * 
	 * @param inventory
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<HeadqInventoryFlowOrderProduct> parseInventoryFile(File inventoryFile) {
		List<HeadqInventoryFlowOrderProduct> orderProducts = new ArrayList<HeadqInventoryFlowOrderProduct>();

		if (inventoryFile != null) {
			InventoryFileTemplate inventoryFileTemplate = new InventoryFileTemplate(inventoryFile);

			Response response = inventoryFileTemplate.process();
			List<Object> returnValues = (List<Object>) response.getReturnValue();
			Map<String, Integer> barcodeMap = (Map<String, Integer>) returnValues.get(0);
			Set<String> barcodes = (Set<String>) returnValues.get(1);

			// 2. prepare the data
			Map<String, ProductBarcode> products = productBarcodeDaoImpl.getProductMapByBarcode(barcodes);

			for (String barcode : barcodes) {
				ProductBarcode product = products.get(barcode);

				if (product == null) {
					loggerLocal.error("Could not find the " + barcode + " in product table");
					continue;
				}

				HeadqInventoryFlowOrderProduct headqInventoryFlowOrderProduct = new HeadqInventoryFlowOrderProduct();
				headqInventoryFlowOrderProduct.setProductBarcode(product);

				Integer quantityI = barcodeMap.get(product.getBarcode());
				int quantity = 0;
				if (quantityI != null)
					quantity = quantityI.intValue();

				headqInventoryFlowOrderProduct.setQuantity(quantity);

				orderProducts.add(headqInventoryFlowOrderProduct);
			}

		}

		return orderProducts;
	}

	/**
	 * to parse the file from the inventory machine
	 * 
	 * @param inventory
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<HeadqInventoryFlowOrderProduct> parseInventoryFile(File inventoryFile, int storeId) {
		List<HeadqInventoryFlowOrderProduct> orderProducts = new ArrayList<HeadqInventoryFlowOrderProduct>();

		if (inventoryFile != null) {
			InventoryFileTemplate inventoryFileTemplate = new InventoryFileTemplate(inventoryFile);

			Response response = inventoryFileTemplate.process();
			List<Object> returnValues = (List<Object>) response.getReturnValue();
			Map<String, Integer> barcodeMap = (Map<String, Integer>) returnValues.get(0);
			Set<String> barcodes = (Set<String>) returnValues.get(1);
			Set<Integer> pbIdSet = productBarcodeDaoImpl.getPBIdsByBarcodes(barcodes);

			HeadQInventoryStore chain = headQInventoryStoreDAOImpl.get(storeId, true);

			// 2. prepare the data
			Map<String, ProductBarcode> products = productBarcodeDaoImpl.getProductMapByBarcode(barcodes);

			// 3. to get the inventory
			Map<String, Integer> inventoryMap = this.getProductsInventoryLevel(pbIdSet, chain.getId());

			for (String barcode : barcodes) {
				ProductBarcode product = products.get(barcode);

				if (product == null) {
					loggerLocal.error("Could not find the " + barcode + " in product table");
					continue;
				}

				HeadqInventoryFlowOrderProduct headqInventoryFlowOrderProduct = new HeadqInventoryFlowOrderProduct();
				headqInventoryFlowOrderProduct.setProductBarcode(product);

				Integer quantityI = barcodeMap.get(product.getBarcode());
				int quantity = 0;
				if (quantityI != null)
					quantity = quantityI.intValue();

				Integer inventoryI = inventoryMap.get(product.getBarcode());
				int inventory = 0;
				if (inventoryI != null)
					inventory = inventoryI.intValue();

				headqInventoryFlowOrderProduct.setQuantity(quantity);
				headqInventoryFlowOrderProduct.setInventoryQ(inventory);
//				headqInventoryFlowOrderProduct.setTotalSalesPrice(quantity * product.getProduct().getSalesPrice());
				headqInventoryFlowOrderProduct.setQuantityDiff(quantity - inventory);

				orderProducts.add(headqInventoryFlowOrderProduct);
			}

		}

		return orderProducts;
	}

	/**
	 * 清空某个库房的叶子树库存
	 * 
	 * @param userInfor
	 * @param storeId
	 * @param yearId
	 * @param quarterId
	 * @param brandId
	 * @param categoryId
	 * @param pbId
	 * @return
	 */
	public Response deleteInventory(UserInfor userInfor, int storeId,int belongTo, int yearId, int quarterId, int brandId,
			int categoryId, int categoryLevelId, int pbId) {
		Response response = new Response();
		// 获取库房
		if (storeId == HeadQInventoryStore.ALL_HEADQ_STORE) {
			List<HeadQInventoryStore> stores = headQInventoryStoreDAOImpl.getActiveStores();
			int rowCount = 0;
			String deleteDetails = "";
			for (HeadQInventoryStore headQInventoryStore : stores) {
					int counts = deleteHeadqInventory(headQInventoryStore.getId(),belongTo, yearId, quarterId, brandId,
							categoryId, categoryLevelId, pbId);
					rowCount += counts;
					deleteDetails += "<br>" + "【" + headQInventoryStore.getName() + "】" + counts + "行数据已经删除";
				}
				response.setSuccess(rowCount + "行数据已经删!除" + "<br>" + "详情如下：" + deleteDetails);
		} else {
			HeadQInventoryStore store = headQInventoryStoreDAOImpl.get(storeId, true);
			if (store != null) {
				int rowCount = deleteHeadqInventory(storeId,belongTo, yearId, quarterId, brandId, categoryId, categoryLevelId,
						pbId);
				response.setSuccess(rowCount + " 行数据已经删除");
			} else {
				response.setFail("无法找到库房");
			}
		}

		return response;
	}

	public int deleteHeadqInventory(int storeId,int belongTo, int yearId, int quarterId, int brandId, int categoryId,
			int categoryLevelId, int pbId) {
		StringBuffer deleteInventory = new StringBuffer( "DELETE FROM HeadQInventoryStock AS his WHERE his.storeId = "  + storeId);
		
		if (yearId != 0 || quarterId != 0 || brandId != 0 || categoryId != 0 || belongTo != Common_util.ALL_RECORD) {
			deleteInventory.append(" AND his.productBarcode.id IN (SELECT pb.id FROM ProductBarcode AS pb WHERE 1=1 ");
			if (yearId != 0) {
				deleteInventory.append(" AND pb.product.year.year_ID="+ yearId);
			}			
			if (quarterId != 0) {
				deleteInventory.append(" AND pb.product.quarter.quarter_ID=" + quarterId);
			}		
			//有品牌带品牌，没品牌带归属
			if (brandId != 0) {
				deleteInventory.append(" AND pb.product.brand.brand_ID=" + brandId);
			}
			
			deleteInventory.append(" AND pb.product.brand.belong_To=" + belongTo);

			if (categoryId != 0) {
				deleteInventory.append(" AND pb.product.category.category_ID=" + categoryId);
			}
			if (categoryLevelId != 0) {
				deleteInventory.append(" AND pb.product.categoryLevel1.category_ID=" + categoryLevelId);
			}
			if (pbId != 0) {
				deleteInventory.append(" AND pb.id=" + pbId);
			}

			deleteInventory.append(")");
		}

		return headQInventoryStockDAOImpl.executeHQLUpdateDelete(deleteInventory.toString(), null, true);
	}


	/**
	 * 下载总部商品库存跟踪
	 * @param path
	 * @param list
	 * @return
	 */
	public Response generateStockExcel(String path, List<HeadqInvenTraceInfoVO> list) {
		Response response = new Response();
		try {			
			HeadqInvenTraceInfoTemplate salesOrdersTemplate = new HeadqInvenTraceInfoTemplate(list,path);
			HSSFWorkbook wb = salesOrdersTemplate.process();
			ByteArrayInputStream byteArrayInputStream = ExcelUtil.convertExcelToInputStream(wb);

			response.setReturnValue(byteArrayInputStream);
			response.setReturnCode(Response.SUCCESS);
		} catch (Exception e) {
			loggerLocal.error(e);
			e.printStackTrace();
			response.setFail(e.getMessage());
		}
		return response;
	}

	/**
	 * 总部合并单据
	 * @param formBean
	 * @param loginUser
	 * @return
	 */
	@SuppressWarnings("unused")
	public Response saveMergeDocument(HeadqInventoryFlowFormBean formBean,UserInfor loginUser)  {
		Response response = new Response();
		if (StringUtils.isNotBlank(formBean.getDocumentIds())) {
			List<String> ids = Arrays.asList(formBean.getDocumentIds().split(","));					
			List<Integer> orderIds = new ArrayList<Integer>();
			HeadqInventoryFlowOrder fOrder =  new HeadqInventoryFlowOrder();
			HeadQInventoryStore checkStore = new HeadQInventoryStore();
			if (ids.size() !=0) {
				fOrder = headqInventoryFlowOrderDaoImpl.selectOrderById(ids.get(0));
				if (fOrder != null) {
					checkStore = headQInventoryStoreDAOImpl.get(fOrder.getStoreId(), true);
				}
			}
			
			for (String id : ids) {
				//校验是否含有非法字符
				if(!Common_util.isNumber(id)) {					
					response.setQuickValue(Response.FAIL, "合并单据号有非法字符，请重新输入单据号");
					return response;
				}
				//校验单据是否是备注单据或者是库存单据草稿
				HeadqInventoryFlowOrder order = headqInventoryFlowOrderDaoImpl.selectOrderById(id);				
				if (order == null) {
					response.setQuickValue(Response.FAIL, "合并单据号：" +id+  "并不是备注单据，也不是库存单草稿，请重新输入单据号");
					return response;
				}
				//校验多个单据是否是同一个库房的单据(注：不同库存的单据不能合并）					
				if (fOrder.getStoreId() != order.getStoreId()) {							
					response.setQuickValue(Response.FAIL, "合并单据号：" +id+  "并不是 "+checkStore.getName() +"库房的备注单据或库存单据，请重新输入单据号");
					return response;
				}
				//校验单据是否是该店铺的备注单据或者是库存单据草稿
				orderIds.add(Integer.valueOf(id));
			}
						
			// 根据条码获取合并后的数量
			List<HeadqInventoryDTO> list = headqInventoryFlowOrderProductDaoImpl.selectByOrderIds(orderIds);
			List<HeadqInventoryFlowOrderProduct> cProducts = new ArrayList<HeadqInventoryFlowOrderProduct>();
			HeadQInventoryStore store = headQInventoryStoreDAOImpl.get(formBean.getFlowOrder().getStoreId(), true);
			
			
			int sumTotal = 0;
			if (list.size() != 0) {
				for (HeadqInventoryDTO hqInventoryDTO : list) {
					ProductBarcode barcode = productBarcodeDaoImpl.get(hqInventoryDTO.getProductId(), true);
					
					int inventoryFlowLevel = headQInventoryStockDAOImpl.getProductStock(barcode.getId(), formBean.getFlowOrder().getStoreId(), true);
					HeadqInventoryFlowOrderProduct cProduct = new HeadqInventoryFlowOrderProduct();
					cProduct.setProductBarcode(barcode);
					cProduct.setQuantity(hqInventoryDTO.getSumQuantity());
					cProduct.setInventoryQ(inventoryFlowLevel);//当前库存实际数量
					cProduct.setTotalCost(barcode.getProduct().getSalesPrice() * hqInventoryDTO.getSumQuantity());
					cProduct.setWholePrice(barcode.getProduct().getWholeSalePrice());
					cProduct.setTotalWholePrice(barcode.getProduct().getWholeSalePrice() * hqInventoryDTO.getSumQuantity());
					cProducts.add(cProduct);					
				}
			}
			
			// 和并单据外的新增条码信息和文件上传的条码
			List<HeadqInventoryFlowOrderProduct> products = null;
		    try {
		       products = parseInventoryFile(formBean.getInventory(), formBean.getFlowOrder().getStoreId());
		    } catch (Exception e) {
				response.setQuickValue(Response.FAIL, "库存文件格式错误");
				return response;
			}

		    //合并单据的条码和新增的条码合在一起
		    List<HeadqInventoryFlowOrderProduct> currentProducts = formBean.getFlowOrder().getProductList();
		    currentProducts.addAll(products);
		    currentProducts.addAll(cProducts);
						
			HeadqInventoryFlowOrder flowOrder = new HeadqInventoryFlowOrder();
			flowOrder.setType(formBean.getFlowOrder().getType()); 
			flowOrder.setStatus(ChainInventoryFlowOrder.STATUS_DRAFT);
			//库房信息
			flowOrder.setStoreId(store.getId());
			flowOrder.setProductList(currentProducts);
			flowOrder.setTotalQuantity(sumTotal);
			flowOrder.setComment("合并单据(" + formBean.getDocumentIds() + ")");
		
	    try {
			save(flowOrder,loginUser);
		} catch (Exception e) {
			e.printStackTrace();
		}
	    response.setMessage("已经成功保存");
	    response.setReturnValue(flowOrder.getId());
	} else {
	    response.setQuickValue(Response.FAIL,"保存合并单据失败");
	}

	return response;
	}
	
	
	public HeadqInventoryFlowOrder excludeUnqualified(HeadqInventoryFlowOrder order) {
		if (order.getProductList().size() !=0) {
			for (int i= 0;i< order.getProductList().size();i++) {
				if (order.getProductList().get(i) == null || order.getProductList().get(i).getProductBarcode().getBarcode().equals("") ) {
					order.getProductList().remove(i);
				}
			}
		}
		return order;
	}

	
	/**
	 * 查询进销存变动统计树信息
	 * @param parentId
	 * @param startDate
	 * @param endDate
	 * @param storeId
	 * @param yearId
	 * @param quarterId
	 * @param brandId
	 * @param categoryLevelId
	 * @param categoryId
	 * @param rptTypeId
	 * @param belongTo
	 * @param userInfor
	 * @return
	 */
	public Response getHeadqInventoryChangeDetails(int parentId, Date startDate, Date endDate,
			String storeIds, int yearId, int quarterId, int brandId, int categoryLevelId, int categoryId, int rptTypeId,
			int belongTo, UserInfor userInfor) {
		System.out.println(storeIds + "," + yearId + "," + quarterId + "," + brandId);
		Response response = new Response();
		boolean isAllStore = false;
		//校验是否是全部库房
		List<HeadQInventoryStore> headStores = headQInventoryStoreDAOImpl.getAll(true);
		String[] ids = null;
		List<Integer> stores = new ArrayList<Integer>();
		Set<Integer> set = new HashSet<Integer>();
		if (StringUtils.isNotBlank(storeIds)) {
			 ids = storeIds.split(",");	
			 for (int i = 0; i < ids.length; i++) {	
				 String idString = ids[i].trim();
				 if(StringUtils.isNotBlank(idString)) {
					 set.add(Integer.valueOf(idString));
				 }			 
			 }
		}
		if (ids == null) {
			isAllStore = true;
		}else if (set.size() == headStores.size() || set.size() == 0) {			
			isAllStore = true;			
		}else {
			for (Integer id: set) {						
				stores.add(id);								
			}
		}

		List<HqInventoryChangeDetailsVO> headqInventoryVOList = new ArrayList<HqInventoryChangeDetailsVO>();

		Date staDate = Common_util.formStartDate(startDate);
		Date eDate = Common_util.formEndDate(endDate);
		if (parentId == 0) {
			//首行合计信息
						String hql;
						List<Object> inventoryData = new ArrayList<Object>();
						HqInventoryChangeDetailsVO inventoryDetailsVo = new HqInventoryChangeDetailsVO();
						
						// 1.取上期数量和上期金额  -- 合计信息
						if (!isAllStore) {
							hql = "SELECT SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and  his.storeId in "+Common_util.parseList2SQLString(stores)+"  AND his.productBarcode.product.brand.belong_To = ?  ";
							Object[] values = {eDate,belongTo};
							inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
						} else {
							hql = "SELECT SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ? and  his.productBarcode.product.brand.belong_To = ? ";
							Object[] values = {eDate,belongTo};
							inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
						}

						if (inventoryData != null) {
							for (Object object : inventoryData) {
								Object[] object2 = (Object[]) object;
								
								int quantity = Common_util.getInt(object2[0]);
								double costTotal = Common_util.getDouble(object2[1]);
													
								inventoryDetailsVo = new HqInventoryChangeDetailsVO(parentId +1, "合计", quantity,
										costTotal, HeadqInventoryVO.STATE_CLOSED, storeIds, 0, quarterId, brandId, categoryId,
										categoryLevelId);
								inventoryDetailsVo.setTotalQuantity(quantity);
								inventoryDetailsVo.setTotalAmount(costTotal);							
							}
						}
						
						//2.取采购模块  -- 合计信息
						List<Object> value_sale = new ArrayList<Object>();
						value_sale.add(staDate);
						value_sale.add(eDate);
						value_sale.add(BaseOrder.STATUS_COMPLETE);
						value_sale.add(belongTo);
						StringBuffer sql;
						if (!isAllStore) {
						
							 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity), p.order.type FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ?  and p.order.status = ?  and p.pb.product.brand.belong_To = ?  and p.order.store.id in "+Common_util.parseList2SQLString(stores)+"   GROUP BY p.order.type");
						}else {
							 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity), p.order.type FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ? and p.order.status = ? and p.pb.product.brand.belong_To = ?  GROUP BY p.order.type");
						}
						List<Object> purchaseValues = purchaseOrderProductDaoImpl.executeHQLSelect(sql.toString(), value_sale.toArray(), null, true);
				
						if (purchaseValues != null){
							for (Object record : purchaseValues ){
								Object[] records = (Object[])record;
								int quantity = Common_util.getInt(records[0]);//数量
								double cost = Common_util.getDouble(records[1]);//成本
								int type = Common_util.getInt(records[2]);//类型
								if (type == PurchaseOrder.TYPE_PURCHASE) {//采购
									inventoryDetailsVo.setPeriodPurchaseNums(quantity);
									inventoryDetailsVo.setPeriodPurchaseMoneys(cost);
								}else if (type == PurchaseOrder.TYPE_RETURN) {//采购退货
									inventoryDetailsVo.setPeriodPurchaseReturnNums(quantity);
									inventoryDetailsVo.setPeriodPurchaseReturnMoneys(cost);
								}else if (type == PurchaseOrder.TYPE_FREE) {//采购赠送
									inventoryDetailsVo.setPeriodReceiveNums(quantity);
									inventoryDetailsVo.setPeriodReceiveMoneys(cost);
								}								
							}														
						}
						
						//3.取销售模块-- 合计信息
						List<Object> value_inventory = new ArrayList<Object>();
						value_inventory.add(staDate);
						value_inventory.add(eDate);
						value_inventory.add(InventoryOrder.STATUS_ACCOUNT_COMPLETE);//取审核完成的单据
						value_inventory.add(belongTo); 
						String criteria;
						if (!isAllStore) {
							
							criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.order.store.id in "+Common_util.parseList2SQLString(stores)+"  GROUP BY csp.order.order_type";
						}else {
							 criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? GROUP BY csp.order.order_type";
						}
						List<Object> inventoryValues = inventoryOrderProductDAOImpl.executeHQLSelect(criteria, value_inventory.toArray(), null, true);
						if (inventoryValues != null){
							for (Object record : inventoryValues ){
								Object[] records = (Object[])record;
								int quantity = Common_util.getInt(records[0]);
								double cost = Common_util.getDouble(records[1]);
								int type = Common_util.getInt(records[2]);
								
								if (type == InventoryOrder.TYPE_SALES_ORDER_W) {//销售
									inventoryDetailsVo.setPeriodSaleNums(quantity);
									inventoryDetailsVo.setPeriodSaleMoneys(cost);										
								}else if(type == InventoryOrder.TYPE_SALES_RETURN_ORDER_W){//销售退货
									inventoryDetailsVo.setPeriodSaleReturnNums(quantity);
									inventoryDetailsVo.setPeriodSaleReturnMoneys(cost);
								}else if (type == InventoryOrder.TYPE_SALES_FREE_ORDER_W) {//销售赠送
									inventoryDetailsVo.setPeriodGiftNums(quantity);
									inventoryDetailsVo.setPeriodGiftMoneys(cost);
								}													
							}								
						}
													
						//4.取库存报溢/报损  -- 合计信息
						String inventorySQL;	
						List<Object> overFlowValues = new ArrayList<Object>();
						if (!isAllStore) {
							inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ? and his.flowOrder.status = ? and  his.flowOrder.storeId in "+Common_util.parseList2SQLString(stores)+" AND  his.productBarcode.product.brand.belong_To = ?  GROUP BY his.flowOrder.type";
							Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo};
							overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
						} else {
							inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ? and his.flowOrder.status = ?  AND  his.productBarcode.product.brand.belong_To = ?  GROUP BY his.flowOrder.type";
							Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo};
							overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
						}						
						if (overFlowValues != null) {
							for (Object object : overFlowValues) {
								Object[] object2 = (Object[]) object;
								
								double costTotal = Common_util.getDouble(object2[0]);
								int quantity = Common_util.getInt(object2[1]);
								int type = Common_util.getInt(object2[2]);
								
								if (type == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {//报溢
									inventoryDetailsVo.setPeriodOverflowNums(quantity);
									inventoryDetailsVo.setPeriodOverflowMoneys(costTotal);
								}else if (type == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER) {//报损
									inventoryDetailsVo.setPeriodLossNums(quantity);
									inventoryDetailsVo.setPeriodLossMoneys(costTotal);
								}																								
							}
						}
						
						//5.取库存调入 指定库房  -- 合计信息
						String callInSql = "";
						List<Object> callinValues = new ArrayList<Object>();
						if(!isAllStore) {
							callInSql = "SELECT  SUM(his.totalCost), SUM(his.quantity) FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ? and his.flowOrder.status = ? and his.flowOrder.toStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ?  ";
							Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo};
							callinValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(callInSql, values, null, true);
						}
						if (callinValues != null) {
							for (Object object : callinValues) {
								Object[] object2 = (Object[]) object;
								
								double costTotal = Common_util.getDouble(object2[0]);
								int quantity = Common_util.getInt(object2[1]);
								
								inventoryDetailsVo.setPeriodCallInNums(quantity);
								inventoryDetailsVo.setPeriodCallInMoneys(costTotal);								
							}
						}
						
						//6.取调出  -- 合计信息
						String outSql = "";
						List<Object> outValues = new ArrayList<Object>();
						if(!isAllStore) {
							outSql = "SELECT  SUM(his.totalCost), SUM(his.quantity) FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ? and his.flowOrder.status = ? and his.flowOrder.fromStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ?  ";
							Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo};
							outValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(outSql, values, null, true);
						}
						if (outValues != null) {
							for (Object object : outValues) {
								Object[] object2 = (Object[]) object;
								
								double costTotal = Common_util.getDouble(object2[0]);
								int quantity = Common_util.getInt(object2[1]);
								
								inventoryDetailsVo.setPeriodOutNums(quantity);
								inventoryDetailsVo.setPeriodOutMoneys(costTotal);								
							}
						}
						
						// 7.取期末数量和期末金额  -- 合计信息
						String endHql;
						List<Object> inventoryEndData = new ArrayList<Object>();
						if (!isAllStore) {
							endHql = "SELECT SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and  his.storeId in "+Common_util.parseList2SQLString(stores)+"  AND his.productBarcode.product.brand.belong_To = ?  ";
							Object[] values = {staDate,belongTo};
							inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
						} else {
							endHql = "SELECT SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ? and  his.productBarcode.product.brand.belong_To = ? ";
							Object[] values = {staDate,belongTo};
							inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
						}

						if (inventoryEndData != null) {
							for (Object object : inventoryEndData) {
								Object[] object2 = (Object[]) object;
								
								int quantity = Common_util.getInt(object2[0]);
								double costTotal = Common_util.getDouble(object2[1]);
								inventoryDetailsVo.setBeforeAmount(quantity);
								inventoryDetailsVo.setBeforeAmountMoney(costTotal);
							
							}
						}
					inventoryDetailsVo.initAmountTo();
					headqInventoryVOList.add(inventoryDetailsVo);
						
						
		}else if (yearId == 0) {
			// @2. 展开所有年份的库存信息
			HashMap<Integer, HqInventoryChangeDetailsVO> hashMap = new HashMap<Integer, HqInventoryChangeDetailsVO>();
			String hql;
			List<Object> inventoryData = new ArrayList<Object>();
			//1.年份 - 期末数量和金额
			if (!isAllStore) {
				hql = "SELECT his.productBarcode.product.year.year_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+"  AND his.productBarcode.product.brand.belong_To = ?  GROUP BY his.productBarcode.product.year.year_ID ORDER BY his.productBarcode.product.year.year_ID ASC";
				Object[] values = {eDate,belongTo};
				inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
			} else {
				hql = "SELECT his.productBarcode.product.year.year_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and  his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.year.year_ID ORDER BY his.productBarcode.product.year.year_ID ASC";
				Object[] values = {eDate,belongTo};
				inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
			}
			
			if (inventoryData != null) {
				for (Object object : inventoryData) {
					Object[] object2 = (Object[]) object;
					int yearIdDB = Common_util.getInt(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					double costTotal = Common_util.getDouble(object2[2]);

					Year year = yearDaoImpl.get(yearIdDB, true);

					HqInventoryChangeDetailsVO inventoryDetailsVo = new HqInventoryChangeDetailsVO(parentId, year.getYear() + "年", quantity,
							costTotal, HeadqInventoryVO.STATE_CLOSED, storeIds, yearIdDB, quarterId, brandId, categoryId,
							categoryLevelId);
					inventoryDetailsVo.setTotalQuantity(quantity);
					inventoryDetailsVo.setTotalAmount(costTotal);
					hashMap.put(yearIdDB, inventoryDetailsVo);
					
				}
			}
			
			//2.年份 - 取采购模块
			List<Object> value_sale = new ArrayList<Object>();
			value_sale.add(staDate);
			value_sale.add(eDate);
			value_sale.add(BaseOrder.STATUS_COMPLETE);
			value_sale.add(belongTo);
			StringBuffer sql;
			if (!isAllStore) {
				
				 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity), p.order.type, p.pb.product.year.year_ID FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ?  and p.order.status = ? and p.pb.product.brand.belong_To = ?  and p.order.store.id in "+Common_util.parseList2SQLString(stores)+"   GROUP BY  p.pb.product.year.year_ID,p.order.type");
			}else {
				 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity), p.order.type, p.pb.product.year.year_ID FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ?  and p.order.status = ? and p.pb.product.brand.belong_To = ? GROUP BY p.pb.product.year.year_ID, p.order.type");
			}
			List<Object> purchaseValues = purchaseOrderProductDaoImpl.executeHQLSelect(sql.toString(), value_sale.toArray(), null, true);
	
			if (purchaseValues != null){
				for (Object record : purchaseValues ){
					Object[] records = (Object[])record;
					int quantity = Common_util.getInt(records[0]);//数量
					double cost = Common_util.getDouble(records[1]);//成本
					int type = Common_util.getInt(records[2]);//类型
					int year = Common_util.getInt(records[3]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(year);
					if(inventoryDetailsVo != null) {
						if (type == PurchaseOrder.TYPE_PURCHASE) {//采购
							inventoryDetailsVo.setPeriodPurchaseNums(quantity);
							inventoryDetailsVo.setPeriodPurchaseMoneys(cost);
						}else if (type == PurchaseOrder.TYPE_RETURN) {//采购退货
							inventoryDetailsVo.setPeriodPurchaseReturnNums(quantity);
							inventoryDetailsVo.setPeriodPurchaseReturnMoneys(cost);
						}else if (type == PurchaseOrder.TYPE_FREE) {//采购赠送
							inventoryDetailsVo.setPeriodReceiveNums(quantity);
							inventoryDetailsVo.setPeriodReceiveMoneys(cost);
						}
					}													
				}														
			}
			
			//3.年份--取销售模块
			List<Object> value_inventory = new ArrayList<Object>();
			value_inventory.add(staDate);
			value_inventory.add(eDate);
			value_inventory.add(InventoryOrder.STATUS_ACCOUNT_COMPLETE);//取审核完成的单据
			value_inventory.add(belongTo); 
			String criteria;
			if (!isAllStore) {
				
				criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.product.year.year_ID  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.order.store.id in "+Common_util.parseList2SQLString(stores)+"  GROUP BY csp.productBarcode.product.year.year_ID, csp.order.order_type";
			}else {
				 criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.product.year.year_ID  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? GROUP BY csp.productBarcode.product.year.year_ID, csp.order.order_type";
			}
			List<Object> inventoryValues = inventoryOrderProductDAOImpl.executeHQLSelect(criteria, value_inventory.toArray(), null, true);
			if (inventoryValues != null){
				for (Object record : inventoryValues ){
					Object[] records = (Object[])record;
					int quantity = Common_util.getInt(records[0]);
					double cost = Common_util.getDouble(records[1]);
					int type = Common_util.getInt(records[2]);
					int year = Common_util.getInt(records[3]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(year);
					if(inventoryDetailsVo != null) {					
						if (type == InventoryOrder.TYPE_SALES_ORDER_W) {//销售
							inventoryDetailsVo.setPeriodSaleNums(quantity);
							inventoryDetailsVo.setPeriodSaleMoneys(cost);										
						}else if(type == InventoryOrder.TYPE_SALES_RETURN_ORDER_W){//销售退货
							inventoryDetailsVo.setPeriodSaleReturnNums(quantity);
							inventoryDetailsVo.setPeriodSaleReturnMoneys(cost);
						}else if (type == InventoryOrder.TYPE_SALES_FREE_ORDER_W) {//销售赠送
							inventoryDetailsVo.setPeriodGiftNums(quantity);
							inventoryDetailsVo.setPeriodGiftMoneys(cost);
						}
					}
				}								
			}
			
			//4 年份--取库存报溢/报损
			String inventorySQL;	
			List<Object> overFlowValues = new ArrayList<Object>();
			if (!isAllStore) {
				inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.product.year.year_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and  his.flowOrder.storeId in "+Common_util.parseList2SQLString(stores)+" AND  his.productBarcode.product.brand.belong_To = ?  GROUP BY his.productBarcode.product.year.year_ID, his.flowOrder.type";
				Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo};
				overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
			} else {
				inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.product.year.year_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ? and his.flowOrder.status = ?  AND  his.productBarcode.product.brand.belong_To = ?  GROUP BY his.productBarcode.product.year.year_ID, his.flowOrder.type";
				Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo};
				overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
			}						
			if (overFlowValues != null) {
				for (Object object : overFlowValues) {
					Object[] object2 = (Object[]) object;
					
					double costTotal = Common_util.getDouble(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					int type = Common_util.getInt(object2[2]);
					int year = Common_util.getInt(object2[3]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(year);
					if(inventoryDetailsVo != null) {	
						if (type == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {//报溢
							inventoryDetailsVo.setPeriodOverflowNums(quantity);
							inventoryDetailsVo.setPeriodOverflowMoneys(costTotal);
						}else if (type == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER) {//报损
							inventoryDetailsVo.setPeriodLossNums(quantity);
							inventoryDetailsVo.setPeriodLossMoneys(costTotal);
						}																								
					}
				}
			}
			
			//5.年份--取库存调入 指定库房  
			String callInSql = "";
			List<Object> callinValues = new ArrayList<Object>();
			if(!isAllStore) {
				callInSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.product.year.year_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and his.flowOrder.toStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ?  GROUP BY his.productBarcode.product.year.year_ID";
				Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo};
				callinValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(callInSql, values, null, true);
			}
			if (callinValues != null) {
				for (Object object : callinValues) {
					Object[] object2 = (Object[]) object;
					
					double costTotal = Common_util.getDouble(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					int year = Common_util.getInt(object2[2]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(year);
						if(inventoryDetailsVo != null) {
						inventoryDetailsVo.setPeriodCallInNums(quantity);
						inventoryDetailsVo.setPeriodCallInMoneys(costTotal);								
					}
				}
			}
			
			//6.年份--取调出  
			String outSql = "";
			List<Object> outValues = new ArrayList<Object>();
			if(!isAllStore) {
				outSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.product.year.year_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ? and his.flowOrder.status = ?  and his.flowOrder.fromStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ?  GROUP BY his.productBarcode.product.year.year_ID";
				Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo};
				outValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(outSql, values, null, true);
			}
			if (outValues != null) {
				for (Object object : outValues) {
					Object[] object2 = (Object[]) object;
					
					double costTotal = Common_util.getDouble(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					int year = Common_util.getInt(object2[2]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(year);
						if(inventoryDetailsVo != null) {
						inventoryDetailsVo.setPeriodOutNums(quantity);
						inventoryDetailsVo.setPeriodOutMoneys(costTotal);								
					}							
				}
			}
			// 7.年份--取上期数量和上期金额 
			String endHql;
			List<Object> inventoryEndData = new ArrayList<Object>();
			if (!isAllStore) {
				endHql = "SELECT his.productBarcode.product.year.year_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+"  AND his.productBarcode.product.brand.belong_To = ?  GROUP BY his.productBarcode.product.year.year_ID ORDER BY his.productBarcode.product.year.year_ID ASC";
				Object[] values = {staDate,belongTo};
				inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
			} else {
				endHql = "SELECT his.productBarcode.product.year.year_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and  his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.year.year_ID ORDER BY his.productBarcode.product.year.year_ID ASC";
				Object[] values = {staDate,belongTo};
				inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
			}
			
			if (inventoryEndData != null) {
				for (Object object : inventoryEndData) {
					Object[] object2 = (Object[]) object;
					int yearIdDB = Common_util.getInt(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					double costTotal = Common_util.getDouble(object2[2]);

					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(yearIdDB);
					if (inventoryDetailsVo != null) {
						inventoryDetailsVo.setBeforeAmount(quantity);
						inventoryDetailsVo.setBeforeAmountMoney(costTotal);		
					}
			
				}
			}
			
			for(Integer yeaInteger: hashMap.keySet()) {
				HqInventoryChangeDetailsVO vo = hashMap.get(yeaInteger);
				vo.initAmountTo();
				headqInventoryVOList.add(vo);
			}
			
			
		} else if (quarterId == 0) {
			// @2. 展开所有季的库存信息
			HashMap<Integer, HqInventoryChangeDetailsVO> hashMap = new HashMap<Integer, HqInventoryChangeDetailsVO>();
			String hql;
			//1.季度 --期末数量和金额
			List<Object> inventoryData = new ArrayList<Object>();
			if (!isAllStore) {
				hql = "SELECT his.productBarcode.product.quarter.quarter_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+" AND his.productBarcode.product.brand.belong_To = ? AND his.productBarcode.product.year.year_ID=? GROUP BY his.productBarcode.product.quarter.quarter_ID ORDER BY his.productBarcode.product.quarter.quarter_ID ASC";
				Object[] values = {eDate, belongTo,yearId};
				inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
			} else {
				hql = "SELECT his.productBarcode.product.quarter.quarter_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.quarter.quarter_ID ORDER BY his.productBarcode.product.quarter.quarter_ID ASC";
				Object[] values = {eDate, yearId,belongTo };
				inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
			}

			if (inventoryData != null) {
				for (Object object : inventoryData) {
					Object[] object2 = (Object[]) object;
					int quarterIdDB = Common_util.getInt(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					double costTotal = Common_util.getDouble(object2[2]);

					Year year = yearDaoImpl.get(yearId, true);
					Quarter quarter = quarterDaoImpl.get(quarterIdDB, true);

					String name = year.getYear() + "年" + quarter.getQuarter_Name();

					HqInventoryChangeDetailsVO inventoryDetailsVo = new HqInventoryChangeDetailsVO(parentId, name, quantity, costTotal,
							HeadqInventoryVO.STATE_CLOSED,storeIds, yearId, quarterIdDB, brandId, categoryId,
							categoryLevelId);
					inventoryDetailsVo.setTotalQuantity(quantity);
					inventoryDetailsVo.setTotalAmount(costTotal);	
					hashMap.put(quarterIdDB, inventoryDetailsVo);
					
				}
			}
			
			//2.季度 - 取采购模块
			List<Object> value_sale = new ArrayList<Object>();
			value_sale.add(staDate);
			value_sale.add(eDate);
			value_sale.add(BaseOrder.STATUS_COMPLETE);
			value_sale.add(belongTo);
			StringBuffer sql;
			if (!isAllStore) {
				value_sale.add(yearId);
				 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity), p.order.type, p.pb.product.quarter.quarter_ID FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ?  and p.order.status = ? and p.pb.product.brand.belong_To = ?  and p.order.store.id in "+Common_util.parseList2SQLString(stores)+" and p.pb.product.year.year_ID = ?   GROUP BY  p.pb.product.quarter.quarter_ID,p.order.type");
			}else {
				value_sale.add(yearId);
				 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity), p.order.type, p.pb.product.quarter.quarter_ID FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ? and p.order.status = ? and p.pb.product.brand.belong_To = ? and p.pb.product.year.year_ID = ?  GROUP BY p.pb.product.quarter.quarter_ID, p.order.type");
			}
			List<Object> purchaseValues = purchaseOrderProductDaoImpl.executeHQLSelect(sql.toString(), value_sale.toArray(), null, true);
	
			if (purchaseValues != null){
				for (Object record : purchaseValues ){
					Object[] records = (Object[])record;
					int quantity = Common_util.getInt(records[0]);//数量
					double cost = Common_util.getDouble(records[1]);//成本
					int type = Common_util.getInt(records[2]);//类型
					int quarterID = Common_util.getInt(records[3]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(quarterID);
					if(inventoryDetailsVo != null) {
						if (type == PurchaseOrder.TYPE_PURCHASE) {//采购
							inventoryDetailsVo.setPeriodPurchaseNums(quantity);
							inventoryDetailsVo.setPeriodPurchaseMoneys(cost);
						}else if (type == PurchaseOrder.TYPE_RETURN) {//采购退货
							inventoryDetailsVo.setPeriodPurchaseReturnNums(quantity);
							inventoryDetailsVo.setPeriodPurchaseReturnMoneys(cost);
						}else if (type == PurchaseOrder.TYPE_FREE) {//采购赠送
							inventoryDetailsVo.setPeriodReceiveNums(quantity);
							inventoryDetailsVo.setPeriodReceiveMoneys(cost);
						}
					}													
				}														
			}
			
			//3.季度--取销售模块
			List<Object> value_inventory = new ArrayList<Object>();
			value_inventory.add(staDate);
			value_inventory.add(eDate);
			value_inventory.add(InventoryOrder.STATUS_ACCOUNT_COMPLETE);//取审核完成的单据
			value_inventory.add(belongTo); 
			String criteria;
			if (!isAllStore) {
				value_inventory.add(yearId);
				criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.product.quarter.quarter_ID  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.order.store.id in "+Common_util.parseList2SQLString(stores)+" and csp.productBarcode.product.year.year_ID = ?  GROUP BY csp.productBarcode.product.quarter.quarter_ID, csp.order.order_type";
			}else {
				value_inventory.add(yearId);
				 criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.product.quarter.quarter_ID  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.productBarcode.product.year.year_ID = ? GROUP BY csp.productBarcode.product.quarter.quarter_ID, csp.order.order_type";
			}
			List<Object> inventoryValues = inventoryOrderProductDAOImpl.executeHQLSelect(criteria, value_inventory.toArray(), null, true);
			if (inventoryValues != null){
				for (Object record : inventoryValues ){
					Object[] records = (Object[])record;
					int quantity = Common_util.getInt(records[0]);
					double cost = Common_util.getDouble(records[1]);
					int type = Common_util.getInt(records[2]);
					int quarterID = Common_util.getInt(records[3]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(quarterID);
					if(inventoryDetailsVo != null) {					
						if (type == InventoryOrder.TYPE_SALES_ORDER_W) {//销售
							inventoryDetailsVo.setPeriodSaleNums(quantity);
							inventoryDetailsVo.setPeriodSaleMoneys(cost);										
						}else if(type == InventoryOrder.TYPE_SALES_RETURN_ORDER_W){//销售退货
							inventoryDetailsVo.setPeriodSaleReturnNums(quantity);
							inventoryDetailsVo.setPeriodSaleReturnMoneys(cost);
						}else if (type == InventoryOrder.TYPE_SALES_FREE_ORDER_W) {//销售赠送
							inventoryDetailsVo.setPeriodGiftNums(quantity);
							inventoryDetailsVo.setPeriodGiftMoneys(cost);
						}
					}
				}								
			}
			
			//4 季度--取库存报溢/报损
			String inventorySQL;	
			List<Object> overFlowValues = new ArrayList<Object>();
			if (!isAllStore) {
				inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.product.quarter.quarter_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and  his.flowOrder.storeId in "+Common_util.parseList2SQLString(stores)+" AND  his.productBarcode.product.brand.belong_To = ? and his.productBarcode.product.year.year_ID = ?  GROUP BY his.productBarcode.product.quarter.quarter_ID, his.flowOrder.type";
				Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId};
				overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
			} else {
				inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.product.quarter.quarter_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ?  AND  his.productBarcode.product.brand.belong_To = ? and his.productBarcode.product.year.year_ID = ? GROUP BY his.productBarcode.product.quarter.quarter_ID, his.flowOrder.type";
				Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId};
				overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
			}						
			if (overFlowValues != null) {
				for (Object object : overFlowValues) {
					Object[] object2 = (Object[]) object;
					
					double costTotal = Common_util.getDouble(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					int type = Common_util.getInt(object2[2]);
					int quarterID = Common_util.getInt(object2[3]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(quarterID);
					if(inventoryDetailsVo != null) {	
						if (type == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {//报溢
							inventoryDetailsVo.setPeriodOverflowNums(quantity);
							inventoryDetailsVo.setPeriodOverflowMoneys(costTotal);
						}else if (type == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER) {//报损
							inventoryDetailsVo.setPeriodLossNums(quantity);
							inventoryDetailsVo.setPeriodLossMoneys(costTotal);
						}																								
					}
				}
			}
			
			//5.季度--取库存调入 指定库房  
			String callInSql = "";
			List<Object> callinValues = new ArrayList<Object>();
			if(!isAllStore) {
				callInSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.product.quarter.quarter_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and his.flowOrder.toStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ?  and  his.productBarcode.product.year.year_ID = ? GROUP BY his.productBarcode.product.quarter.quarter_ID";
				Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId};
				callinValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(callInSql, values, null, true);
			}
			if (callinValues != null) {
				for (Object object : callinValues) {
					Object[] object2 = (Object[]) object;
					
					double costTotal = Common_util.getDouble(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					int quarterID = Common_util.getInt(object2[2]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(quarterID);
						if(inventoryDetailsVo != null) {
						inventoryDetailsVo.setPeriodCallInNums(quantity);
						inventoryDetailsVo.setPeriodCallInMoneys(costTotal);								
					}
				}
			}
			
			//6.季度--取调出  
			String outSql = "";
			List<Object> outValues = new ArrayList<Object>();
			if(!isAllStore) {
				outSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.product.quarter.quarter_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and his.flowOrder.fromStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ? and  his.productBarcode.product.year.year_ID = ?  GROUP BY his.productBarcode.product.quarter.quarter_ID";
				Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId};
				outValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(outSql, values, null, true);
			}
			if (outValues != null) {
				for (Object object : outValues) {
					Object[] object2 = (Object[]) object;
					
					double costTotal = Common_util.getDouble(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					int quarterID = Common_util.getInt(object2[2]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(quarterID);
						if(inventoryDetailsVo != null) {
							inventoryDetailsVo.setPeriodOutNums(quantity);
							inventoryDetailsVo.setPeriodOutMoneys(costTotal);								
					}							
				}
			}
			//7.季度 --上期数量和金额
			String endHql;
			List<Object> inventoryEndData = new ArrayList<Object>();
			if (!isAllStore) {
				endHql = "SELECT his.productBarcode.product.quarter.quarter_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+" AND his.productBarcode.product.brand.belong_To = ? AND his.productBarcode.product.year.year_ID=? GROUP BY his.productBarcode.product.quarter.quarter_ID ORDER BY his.productBarcode.product.quarter.quarter_ID ASC";
				Object[] values = {staDate,belongTo,yearId};
				inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
			} else {
				endHql = "SELECT his.productBarcode.product.quarter.quarter_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.quarter.quarter_ID ORDER BY his.productBarcode.product.quarter.quarter_ID ASC";
				Object[] values = {staDate, yearId,belongTo };
				inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
			}

			if (inventoryEndData != null) {
				for (Object object : inventoryEndData) {
					Object[] object2 = (Object[]) object;
					int quarterIdDB = Common_util.getInt(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					double costTotal = Common_util.getDouble(object2[2]);

					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(quarterIdDB);
					inventoryDetailsVo.setBeforeAmount(quantity);
					inventoryDetailsVo.setBeforeAmountMoney(costTotal);
					
				}
			}
			
			for(Integer quarterInteger: hashMap.keySet()) {
				HqInventoryChangeDetailsVO vo = hashMap.get(quarterInteger);
				vo.initAmountTo();
				headqInventoryVOList.add(vo);
			}
			
			
		} else {
			// by brand
			if (rptTypeId == 1) {
				if (brandId == 0) {
					// @ 展开所有品霞的库存信息
					//1.品牌--期末数量和金额
					HashMap<Integer, HqInventoryChangeDetailsVO> hashMap = new HashMap<Integer, HqInventoryChangeDetailsVO>();
					String hql;
					List<Object> inventoryData = new ArrayList<Object>();

					if (!isAllStore) {
						hql = "SELECT his.productBarcode.product.brand.brand_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+" AND his.productBarcode.product.brand.belong_To = ? AND his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? GROUP BY his.productBarcode.product.brand.brand_ID ORDER BY his.productBarcode.product.brand.brand_ID ASC";
						Object[] values = {eDate,belongTo, yearId, quarterId };
						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					} else {
						hql = "SELECT his.productBarcode.product.brand.brand_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and  his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=?  AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.brand.brand_ID ORDER BY his.productBarcode.product.brand.brand_ID ASC";
						Object[] values = { eDate,yearId, quarterId ,belongTo};
						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					}

					if (inventoryData != null) {
						for (Object object : inventoryData) {
							Object[] object2 = (Object[]) object;
							int brandIdDB = Common_util.getInt(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							double costTotal = Common_util.getDouble(object2[2]);

							Brand brand = brandDaoImpl.get(brandIdDB, true);

							String name = "";
							String pinyin = brand.getPinyin();
							if (!StringUtils.isEmpty(pinyin)) {
								name = pinyin.substring(0, 1) + " ";
							}

							name = brand.getBrand_Name();

							HqInventoryChangeDetailsVO inventoryDetailsVo = new HqInventoryChangeDetailsVO(parentId, name, quantity,
									costTotal, HeadqInventoryVO.STATE_CLOSED,storeIds, yearId, quarterId, brandIdDB,
									categoryId, categoryLevelId);
							inventoryDetailsVo.setTotalQuantity(quantity);
							inventoryDetailsVo.setTotalAmount(costTotal);	
							hashMap.put(brandIdDB, inventoryDetailsVo);
							
						}
					}
					//2.品牌--取采购模块
					List<Object> value_sale = new ArrayList<Object>();
					value_sale.add(staDate);
					value_sale.add(eDate);
					value_sale.add(BaseOrder.STATUS_COMPLETE);
					value_sale.add(belongTo);
					StringBuffer sql;
					if (!isAllStore) {
						value_sale.add(yearId);
						value_sale.add(quarterId);
						 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity), p.order.type, p.pb.product.brand.brand_ID FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ? and p.order.status = ? and p.pb.product.brand.belong_To = ?  and p.order.store.id in "+Common_util.parseList2SQLString(stores)+" and p.pb.product.year.year_ID = ? AND p.pb.product.quarter.quarter_ID=?   GROUP BY  p.pb.product.brand.brand_ID,p.order.type");
					}else {
						value_sale.add(yearId);
						value_sale.add(quarterId);
						 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity), p.order.type, p.pb.product.brand.brand_ID FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ? and p.order.status = ? and p.pb.product.brand.belong_To = ? and p.pb.product.year.year_ID = ?  AND p.pb.product.quarter.quarter_ID=?  GROUP BY p.pb.product.brand.brand_ID, p.order.type");
					}
					List<Object> purchaseValues = purchaseOrderProductDaoImpl.executeHQLSelect(sql.toString(), value_sale.toArray(), null, true);
			
					if (purchaseValues != null){
						for (Object record : purchaseValues ){
							Object[] records = (Object[])record;
							int quantity = Common_util.getInt(records[0]);//数量
							double cost = Common_util.getDouble(records[1]);//成本
							int type = Common_util.getInt(records[2]);//类型
							int brandIdDB = Common_util.getInt(records[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(brandIdDB);
							if(inventoryDetailsVo != null) {
								if (type == PurchaseOrder.TYPE_PURCHASE) {//采购
									inventoryDetailsVo.setPeriodPurchaseNums(quantity);
									inventoryDetailsVo.setPeriodPurchaseMoneys(cost);
								}else if (type == PurchaseOrder.TYPE_RETURN) {//采购退货
									inventoryDetailsVo.setPeriodPurchaseReturnNums(quantity);
									inventoryDetailsVo.setPeriodPurchaseReturnMoneys(cost);
								}else if (type == PurchaseOrder.TYPE_FREE) {//采购赠送
									inventoryDetailsVo.setPeriodReceiveNums(quantity);
									inventoryDetailsVo.setPeriodReceiveMoneys(cost);
								}
							}													
						}														
					}
					//3.品牌 --取销售模块
					List<Object> value_inventory = new ArrayList<Object>();
					value_inventory.add(staDate);
					value_inventory.add(eDate);
					value_inventory.add(InventoryOrder.STATUS_ACCOUNT_COMPLETE);//取审核完成的单据
					value_inventory.add(belongTo); 
					String criteria;
					if (!isAllStore) {
						value_inventory.add(yearId);
						value_inventory.add(quarterId);
						criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.product.brand.brand_ID  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.order.store.id in "+Common_util.parseList2SQLString(stores)+" and csp.productBarcode.product.year.year_ID = ? and csp.productBarcode.product.quarter.quarter_ID = ?  GROUP BY csp.productBarcode.product.brand.brand_ID, csp.order.order_type";
					}else {
						value_inventory.add(yearId);
						value_inventory.add(quarterId);
						 criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.product.brand.brand_ID  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.productBarcode.product.year.year_ID = ? and csp.productBarcode.product.quarter.quarter_ID = ?  GROUP BY csp.productBarcode.product.brand.brand_ID, csp.order.order_type";
					}
					List<Object> inventoryValues = inventoryOrderProductDAOImpl.executeHQLSelect(criteria, value_inventory.toArray(), null, true);
					if (inventoryValues != null){
						for (Object record : inventoryValues ){
							Object[] records = (Object[])record;
							int quantity = Common_util.getInt(records[0]);
							double cost = Common_util.getDouble(records[1]);
							int type = Common_util.getInt(records[2]);
							int brandIdDB = Common_util.getInt(records[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(brandIdDB);
							if(inventoryDetailsVo != null) {					
								if (type == InventoryOrder.TYPE_SALES_ORDER_W) {//销售
									inventoryDetailsVo.setPeriodSaleNums(quantity);
									inventoryDetailsVo.setPeriodSaleMoneys(cost);										
								}else if(type == InventoryOrder.TYPE_SALES_RETURN_ORDER_W){//销售退货
									inventoryDetailsVo.setPeriodSaleReturnNums(quantity);
									inventoryDetailsVo.setPeriodSaleReturnMoneys(cost);
								}else if (type == InventoryOrder.TYPE_SALES_FREE_ORDER_W) {//销售赠送
									inventoryDetailsVo.setPeriodGiftNums(quantity);
									inventoryDetailsVo.setPeriodGiftMoneys(cost);
								}
							}
						}								
					}
					
					//4 品牌--取库存报溢/报损
					String inventorySQL;	
					List<Object> overFlowValues = new ArrayList<Object>();
					if (!isAllStore) {
						inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.product.brand.brand_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and  his.flowOrder.storeId in "+Common_util.parseList2SQLString(stores)+" AND  his.productBarcode.product.brand.belong_To = ? and his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ?  GROUP BY his.productBarcode.product.brand.brand_ID, his.flowOrder.type";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId};
						overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
					} else {
						inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.product.brand.brand_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ?  AND  his.productBarcode.product.brand.belong_To = ? and his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? GROUP BY his.productBarcode.product.brand.brand_ID, his.flowOrder.type";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId};
						overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
					}						
					if (overFlowValues != null) {
						for (Object object : overFlowValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int type = Common_util.getInt(object2[2]);
							int brandIdDB = Common_util.getInt(object2[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(brandIdDB);
							if(inventoryDetailsVo != null) {	
								if (type == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {//报溢
									inventoryDetailsVo.setPeriodOverflowNums(quantity);
									inventoryDetailsVo.setPeriodOverflowMoneys(costTotal);
								}else if (type == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER) {//报损
									inventoryDetailsVo.setPeriodLossNums(quantity);
									inventoryDetailsVo.setPeriodLossMoneys(costTotal);
								}																								
							}
						}
					}
					
					//5.品牌--取库存调入 指定库房  
					String callInSql = "";
					List<Object> callinValues = new ArrayList<Object>();
					if (!isAllStore) {
						callInSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.product.brand.brand_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and his.flowOrder.toStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ?  and  his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? GROUP BY his.productBarcode.product.brand.brand_ID";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId};
						callinValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(callInSql, values, null, true);
					}
					if (callinValues != null) {
						for (Object object : callinValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int brandIdDB = Common_util.getInt(object2[2]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(brandIdDB);
								if(inventoryDetailsVo != null) {
								inventoryDetailsVo.setPeriodCallInNums(quantity);
								inventoryDetailsVo.setPeriodCallInMoneys(costTotal);								
							}
						}
					}
					
					//6.品牌--取调出  
					String outSql = "";
					List<Object> outValues = new ArrayList<Object>();
					if (!isAllStore) {
						outSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.product.brand.brand_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and his.flowOrder.fromStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ? and  his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ?  GROUP BY his.productBarcode.product.brand.brand_ID";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId};
						outValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(outSql, values, null, true);
					}
					if (outValues != null) {
						for (Object object : outValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int brandIdDB = Common_util.getInt(object2[2]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(brandIdDB);
								if(inventoryDetailsVo != null) {
									inventoryDetailsVo.setPeriodOutNums(quantity);
									inventoryDetailsVo.setPeriodOutMoneys(costTotal);									
							}							
						}
					}
					// 7.品牌--取上期数量和上期金额  
					String endHql;
					List<Object> inventoryEndData = new ArrayList<Object>();

					if (!isAllStore) {
						endHql = "SELECT his.productBarcode.product.brand.brand_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+" AND his.productBarcode.product.brand.belong_To = ? AND his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? GROUP BY his.productBarcode.product.brand.brand_ID ORDER BY his.productBarcode.product.brand.brand_ID ASC";
						Object[] values = {staDate,belongTo, yearId, quarterId };
						inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
					} else {
						endHql = "SELECT his.productBarcode.product.brand.brand_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and  his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=?  AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.brand.brand_ID ORDER BY his.productBarcode.product.brand.brand_ID ASC";
						Object[] values = { staDate,yearId, quarterId ,belongTo};
						inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
					}

					if (inventoryEndData != null) {
						for (Object object : inventoryEndData) {
							Object[] object2 = (Object[]) object;
							int brandIdDB = Common_util.getInt(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							double costTotal = Common_util.getDouble(object2[2]);

							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(brandIdDB);
							inventoryDetailsVo.setBeforeAmount(quantity);
							inventoryDetailsVo.setBeforeAmountMoney(costTotal);

							
						}
					}
					
					for(Integer quarterInteger: hashMap.keySet()) {
						HqInventoryChangeDetailsVO vo = hashMap.get(quarterInteger);
						vo.initAmountTo();
						headqInventoryVOList.add(vo);
					}
					
				} else if (brandId != 0) {
					// @2. 展开当前品霞的库存信息
					//1.品牌查找-最后一级--期末数量和金额
					String hql;
					HashMap<Integer, HqInventoryChangeDetailsVO> hashMap = new HashMap<Integer, HqInventoryChangeDetailsVO>();
					List<Object> inventoryData = new ArrayList<Object>();

					if (!isAllStore) {
						hql = "SELECT his.productBarcode.id, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+" AND his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.brand.brand_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.id ORDER BY his.productBarcode.product.productCode ASC ";
						Object[] values = { eDate, yearId, quarterId, brandId ,belongTo};
						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					} else {
						hql = "SELECT his.productBarcode.id, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.brand.brand_ID=?  AND his.productBarcode.product.brand.belong_To = ?  GROUP BY his.productBarcode.id ORDER BY his.productBarcode.product.productCode ASC ";
						Object[] values = { eDate,yearId, quarterId, brandId ,belongTo};
						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					}

					if (inventoryData != null) {
						for (Object object : inventoryData) {
							Object[] object2 = (Object[]) object;
							int pbId = Common_util.getInt(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							double costTotal = Common_util.getDouble(object2[2]);

							ProductBarcode pb = productBarcodeDaoImpl.get(pbId, true);
							Color color = pb.getColor();
							String colorName = "";
							if (color != null)
								colorName = color.getName();
							Product product = pb.getProduct();
							String gender = "";
							String sizeRange = "";

							Category category = product.getCategory();
							String name = Common_util.cutProductCode(pb.getProduct().getProductCode()) + colorName + " "
									+ gender + sizeRange + category.getCategory_Name();
							


							HqInventoryChangeDetailsVO inventoryDetailsVo = new HqInventoryChangeDetailsVO(parentId, name, quantity,
									costTotal, HeadqInventoryVO.STATE_OPEN,storeIds, yearId, quarterId, brandId,
									categoryId, categoryLevelId);
							inventoryDetailsVo.setPbId(pbId);
							inventoryDetailsVo.setTotalQuantity(quantity);
							inventoryDetailsVo.setTotalAmount(costTotal);	

							hashMap.put(pbId, inventoryDetailsVo);
						}
					}
					
					//2.品牌查找-最后一级--取采购模块
					List<Object> value_sale = new ArrayList<Object>();
					value_sale.add(staDate);
					value_sale.add(eDate);
					value_sale.add(BaseOrder.STATUS_COMPLETE);
					value_sale.add(belongTo);
					StringBuffer sql;
					if (!isAllStore) {
						value_sale.add(yearId);
						value_sale.add(quarterId);
						value_sale.add(brandId);
						 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity),p.order.type, p.pb.id FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ? and p.order.status = ? and p.pb.product.brand.belong_To = ?  and p.order.store.id in "+Common_util.parseList2SQLString(stores)+" and p.pb.product.year.year_ID = ? AND p.pb.product.quarter.quarter_ID=?  AND p.pb.product.brand.brand_ID=?  GROUP BY  p.pb.id, p.order.type ORDER BY p.pb.product.productCode ASC");
					}else {
						value_sale.add(yearId);
						value_sale.add(quarterId);
						value_sale.add(brandId);
						 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity),p.order.type, p.pb.id FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ? and p.order.status = ? and p.pb.product.brand.belong_To = ? and p.pb.product.year.year_ID = ?  AND p.pb.product.quarter.quarter_ID=? AND p.pb.product.brand.brand_ID=?  GROUP BY p.pb.id, p.order.type ORDER BY p.pb.product.productCode ASC");
					}
					List<Object> purchaseValues = purchaseOrderProductDaoImpl.executeHQLSelect(sql.toString(), value_sale.toArray(), null, true);
			
					if (purchaseValues != null){
						for (Object record : purchaseValues ){
							Object[] records = (Object[])record;
							int quantity = Common_util.getInt(records[0]);//数量
							double cost = Common_util.getDouble(records[1]);//成本
							int type = Common_util.getInt(records[2]);//类型
							int brandIdDB = Common_util.getInt(records[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(brandIdDB);
							if(inventoryDetailsVo != null) {
								if (type == PurchaseOrder.TYPE_PURCHASE) {//采购
									inventoryDetailsVo.setPeriodPurchaseNums(quantity);
									inventoryDetailsVo.setPeriodPurchaseMoneys(cost);
								}else if (type == PurchaseOrder.TYPE_RETURN) {//采购退货
									inventoryDetailsVo.setPeriodPurchaseReturnNums(quantity);
									inventoryDetailsVo.setPeriodPurchaseReturnMoneys(cost);
								}else if (type == PurchaseOrder.TYPE_FREE) {//采购赠送
									inventoryDetailsVo.setPeriodReceiveNums(quantity);
									inventoryDetailsVo.setPeriodReceiveMoneys(cost);
								}
							}													
						}														
					}
					
					//3.品牌查找-最后一级 --取销售模块
					List<Object> value_inventory = new ArrayList<Object>();
					value_inventory.add(staDate);
					value_inventory.add(eDate);
					value_inventory.add(InventoryOrder.STATUS_ACCOUNT_COMPLETE);//取审核完成的单据
					value_inventory.add(belongTo); 
					String criteria;
					if (!isAllStore) {
						value_inventory.add(yearId);
						value_inventory.add(quarterId);
						value_inventory.add(brandId);
						criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.id  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.order.store.id in "+Common_util.parseList2SQLString(stores)+" and csp.productBarcode.product.year.year_ID = ? and csp.productBarcode.product.quarter.quarter_ID = ?  and csp.productBarcode.product.brand.brand_ID=? GROUP BY csp.productBarcode.id, csp.order.order_type";
					}else {
						value_inventory.add(yearId);
						value_inventory.add(quarterId);
						value_inventory.add(brandId);
						 criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.id  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.productBarcode.product.year.year_ID = ? and csp.productBarcode.product.quarter.quarter_ID = ? and csp.productBarcode.product.brand.brand_ID=? GROUP BY csp.productBarcode.id, csp.order.order_type";
					}
					List<Object> inventoryValues = inventoryOrderProductDAOImpl.executeHQLSelect(criteria, value_inventory.toArray(), null, true);
					if (inventoryValues != null){
						for (Object record : inventoryValues ){
							Object[] records = (Object[])record;
							int quantity = Common_util.getInt(records[0]);
							double cost = Common_util.getDouble(records[1]);
							int type = Common_util.getInt(records[2]);
							int pbId = Common_util.getInt(records[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(pbId);
							if(inventoryDetailsVo != null) {					
								if (type == InventoryOrder.TYPE_SALES_ORDER_W) {//销售
									inventoryDetailsVo.setPeriodSaleNums(quantity);
									inventoryDetailsVo.setPeriodSaleMoneys(cost);										
								}else if(type == InventoryOrder.TYPE_SALES_RETURN_ORDER_W){//销售退货
									inventoryDetailsVo.setPeriodSaleReturnNums(quantity);
									inventoryDetailsVo.setPeriodSaleReturnMoneys(cost);
								}else if (type == InventoryOrder.TYPE_SALES_FREE_ORDER_W) {//销售赠送
									inventoryDetailsVo.setPeriodGiftNums(quantity);
									inventoryDetailsVo.setPeriodGiftMoneys(cost);
								}
							}
						}								
					}
					
					//4 品牌查找-最后一级--取库存报溢/报损
					String inventorySQL;	
					List<Object> overFlowValues = new ArrayList<Object>();
					if (!isAllStore) {
						inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.id FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and  his.flowOrder.storeId in "+Common_util.parseList2SQLString(stores)+" AND  his.productBarcode.product.brand.belong_To = ? and his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? and his.productBarcode.product.brand.brand_ID=? GROUP BY his.productBarcode.id , his.flowOrder.type";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId,brandId};
						overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
					} else {
						inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.id FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ?  AND  his.productBarcode.product.brand.belong_To = ? and his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? and his.productBarcode.product.brand.brand_ID=? GROUP BY his.productBarcode.id , his.flowOrder.type";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId,brandId};
						overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
					}						
					if (overFlowValues != null) {
						for (Object object : overFlowValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int type = Common_util.getInt(object2[2]);
							int pbId = Common_util.getInt(object2[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(pbId);
							if(inventoryDetailsVo != null) {	
								if (type == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {//报溢
									inventoryDetailsVo.setPeriodOverflowNums(quantity);
									inventoryDetailsVo.setPeriodOverflowMoneys(costTotal);
								}else if (type == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER) {//报损
									inventoryDetailsVo.setPeriodLossNums(quantity);
									inventoryDetailsVo.setPeriodLossMoneys(costTotal);
								}																								
							}
						}
					}
					
					//5.品牌查找-最后一级-取库存调入 指定库房  
					String callInSql = "";
					List<Object> callinValues = new ArrayList<Object>();
					if(!isAllStore) {
						callInSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.id FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and his.flowOrder.toStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ?  and  his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? and his.productBarcode.product.brand.brand_ID=? GROUP BY his.productBarcode.id";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId,brandId};
						callinValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(callInSql, values, null, true);
					}
					if (callinValues != null) {
						for (Object object : callinValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int brandIdDB = Common_util.getInt(object2[2]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(brandIdDB);
								if(inventoryDetailsVo != null) {
								inventoryDetailsVo.setPeriodCallInNums(quantity);
								inventoryDetailsVo.setPeriodCallInMoneys(costTotal);								
							}
						}
					}
					
					//6.品牌查找-最后一级---取调出  
					String outSql = "";
					List<Object> outValues = new ArrayList<Object>();
					if(!isAllStore) {
						outSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.id FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and his.flowOrder.fromStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ? and  his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? and his.productBarcode.product.brand.brand_ID=?  GROUP BY his.productBarcode.id ";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId,brandId};
						outValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(outSql, values, null, true);
					}
					if (outValues != null) {
						for (Object object : outValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int brandIdDB = Common_util.getInt(object2[2]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(brandIdDB);
								if(inventoryDetailsVo != null) {
									inventoryDetailsVo.setPeriodOutNums(quantity);
									inventoryDetailsVo.setPeriodOutMoneys(costTotal);									
							}							
						}
					}
					// 7.品牌查找-最后一级--取上期数量和上期金额 
					String endHql;
					List<Object> inventoryEndData = new ArrayList<Object>();

					if (!isAllStore) {
						endHql = "SELECT his.productBarcode.id, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+" AND his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.brand.brand_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.id ORDER BY his.productBarcode.product.productCode ASC ";
						Object[] values = { staDate, yearId, quarterId, brandId ,belongTo};
						inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
					} else {
						endHql = "SELECT his.productBarcode.id, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.brand.brand_ID=?  AND his.productBarcode.product.brand.belong_To = ?  GROUP BY his.productBarcode.id ORDER BY his.productBarcode.product.productCode ASC ";
						Object[] values = { staDate,yearId, quarterId, brandId ,belongTo};
						inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
					}

					if (inventoryEndData != null) {
						for (Object object : inventoryEndData) {
							Object[] object2 = (Object[]) object;
							int pbId = Common_util.getInt(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							double costTotal = Common_util.getDouble(object2[2]);

							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(pbId);
							inventoryDetailsVo.setBeforeAmount(quantity);
							inventoryDetailsVo.setBeforeAmountMoney(costTotal);

						}
					}	
					
					
					for(Integer quarterInteger: hashMap.keySet()) {
						HqInventoryChangeDetailsVO vo = hashMap.get(quarterInteger);
						vo.initAmountTo();
						headqInventoryVOList.add(vo);
					}	
				}
			} else if (rptTypeId == 2) {

				if (categoryLevelId == 0) {
					// @2. 展开所有品霞的库存信息
					// 1.产品线 --期末数量和金额
					HashMap<Integer, HqInventoryChangeDetailsVO> hashMap = new HashMap<Integer, HqInventoryChangeDetailsVO>();
					String hql;
					List<Object> inventoryData = new ArrayList<Object>();
					if (!isAllStore) {
						hql = "SELECT his.productBarcode.product.categoryLevel1.category_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date <= ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+"  AND his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.categoryLevel1.category_ID";
						Object[] values = { eDate, yearId, quarterId ,belongTo};
						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					} else {
						hql = "SELECT his.productBarcode.product.categoryLevel1.category_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE  his.date <= ?  and his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.categoryLevel1.category_ID";
						Object[] values = { eDate,yearId, quarterId,belongTo };
						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					}

					if (inventoryData != null) {
						for (Object object : inventoryData) {
							Object[] object2 = (Object[]) object;
							int categoryLevel1Id = Common_util.getInt(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							double costTotal = Common_util.getDouble(object2[2]);

							Category catgory = categoryDaoImpl.get(categoryLevel1Id, true);
							String name = catgory.getCategory_Name();

							HqInventoryChangeDetailsVO inventoryDetailsVo = new HqInventoryChangeDetailsVO(parentId, name, quantity,
									costTotal, HeadqInventoryVO.STATE_CLOSED, storeIds,yearId, quarterId, brandId,
									categoryId, categoryLevel1Id);
							inventoryDetailsVo.setTotalQuantity(quantity);
							inventoryDetailsVo.setTotalAmount(costTotal);	
							hashMap.put(categoryLevel1Id, inventoryDetailsVo);
						}
					}
					
					//2.产品线--取采购模块
					List<Object> value_sale = new ArrayList<Object>();
					value_sale.add(staDate);
					value_sale.add(eDate);
					value_sale.add(BaseOrder.STATUS_COMPLETE);
					value_sale.add(belongTo);
					StringBuffer sql;
					if (!isAllStore) {
						value_sale.add(yearId);
						value_sale.add(quarterId);
						 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity), p.order.type, p.pb.product.categoryLevel1.category_ID FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ? and p.order.status = ? and p.pb.product.brand.belong_To = ?  and p.order.store.id in "+Common_util.parseList2SQLString(stores)+" and p.pb.product.year.year_ID = ? AND p.pb.product.quarter.quarter_ID=?   GROUP BY  p.pb.product.categoryLevel1.category_ID,p.order.type");
					}else {
						value_sale.add(yearId);
						value_sale.add(quarterId);
						 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity), p.order.type, p.pb.product.categoryLevel1.category_ID FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ? and p.order.status = ? and p.pb.product.brand.belong_To = ? and p.pb.product.year.year_ID = ?  AND p.pb.product.quarter.quarter_ID=?  GROUP BY p.pb.product.categoryLevel1.category_ID, p.order.type");
					}
					List<Object> purchaseValues = purchaseOrderProductDaoImpl.executeHQLSelect(sql.toString(), value_sale.toArray(), null, true);
			
					if (purchaseValues != null){
						for (Object record : purchaseValues ){
							Object[] records = (Object[])record;
							int quantity = Common_util.getInt(records[0]);//数量
							double cost = Common_util.getDouble(records[1]);//成本
							int type = Common_util.getInt(records[2]);//类型
							int categoryLevel1Id = Common_util.getInt(records[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(categoryLevel1Id);
							if(inventoryDetailsVo != null) {
								if (type == PurchaseOrder.TYPE_PURCHASE) {//采购
									inventoryDetailsVo.setPeriodPurchaseNums(quantity);
									inventoryDetailsVo.setPeriodPurchaseMoneys(cost);
								}else if (type == PurchaseOrder.TYPE_RETURN) {//采购退货
									inventoryDetailsVo.setPeriodPurchaseReturnNums(quantity);
									inventoryDetailsVo.setPeriodPurchaseReturnMoneys(cost);
								}else if (type == PurchaseOrder.TYPE_FREE) {//采购赠送
									inventoryDetailsVo.setPeriodReceiveNums(quantity);
									inventoryDetailsVo.setPeriodReceiveMoneys(cost);
								}
							}													
						}														
					}
					
					//3.产品线 --取销售模块
					List<Object> value_inventory = new ArrayList<Object>();
					value_inventory.add(staDate);
					value_inventory.add(eDate);
					value_inventory.add(InventoryOrder.STATUS_ACCOUNT_COMPLETE);//取审核完成的单据
					value_inventory.add(belongTo); 
					String criteria;
					if (!isAllStore) {
						value_inventory.add(yearId);
						value_inventory.add(quarterId);
						criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.product.categoryLevel1.category_ID  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.order.store.id in "+Common_util.parseList2SQLString(stores)+" and csp.productBarcode.product.year.year_ID = ? and csp.productBarcode.product.quarter.quarter_ID = ?  GROUP BY csp.productBarcode.product.categoryLevel1.category_ID, csp.order.order_type";
					}else {
						value_inventory.add(yearId);
						value_inventory.add(quarterId);
						 criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.product.categoryLevel1.category_ID  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.productBarcode.product.year.year_ID = ? and csp.productBarcode.product.quarter.quarter_ID = ?  GROUP BY csp.productBarcode.product.categoryLevel1.category_ID, csp.order.order_type";
					}
					List<Object> inventoryValues = inventoryOrderProductDAOImpl.executeHQLSelect(criteria, value_inventory.toArray(), null, true);
					if (inventoryValues != null){
						for (Object record : inventoryValues ){
							Object[] records = (Object[])record;
							int quantity = Common_util.getInt(records[0]);
							double cost = Common_util.getDouble(records[1]);
							int type = Common_util.getInt(records[2]);
							int categoryLevel1Id = Common_util.getInt(records[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(categoryLevel1Id);
							if(inventoryDetailsVo != null) {					
								if (type == InventoryOrder.TYPE_SALES_ORDER_W) {//销售
									inventoryDetailsVo.setPeriodSaleNums(quantity);
									inventoryDetailsVo.setPeriodSaleMoneys(cost);										
								}else if(type == InventoryOrder.TYPE_SALES_RETURN_ORDER_W){//销售退货
									inventoryDetailsVo.setPeriodSaleReturnNums(quantity);
									inventoryDetailsVo.setPeriodSaleReturnMoneys(cost);
								}else if (type == InventoryOrder.TYPE_SALES_FREE_ORDER_W) {//销售赠送
									inventoryDetailsVo.setPeriodGiftNums(quantity);
									inventoryDetailsVo.setPeriodGiftMoneys(cost);
								}
							}
						}								
					}
					
					//4 产品线--取库存报溢/报损
					String inventorySQL;	
					List<Object> overFlowValues = new ArrayList<Object>();
					if (!isAllStore) {
						inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.product.categoryLevel1.category_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and  his.flowOrder.storeId in "+Common_util.parseList2SQLString(stores)+" AND  his.productBarcode.product.brand.belong_To = ? and his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ?  GROUP BY his.productBarcode.product.categoryLevel1.category_ID, his.flowOrder.type";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId};
						overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
					} else {
						inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.product.categoryLevel1.category_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ?  AND  his.productBarcode.product.brand.belong_To = ? and his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? GROUP BY his.productBarcode.product.categoryLevel1.category_ID, his.flowOrder.type";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId};
						overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
					}						
					if (overFlowValues != null) {
						for (Object object : overFlowValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int type = Common_util.getInt(object2[2]);
							int categoryLevel1Id = Common_util.getInt(object2[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(categoryLevel1Id);
							if(inventoryDetailsVo != null) {	
								if (type == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {//报溢
									inventoryDetailsVo.setPeriodOverflowNums(quantity);
									inventoryDetailsVo.setPeriodOverflowMoneys(costTotal);
								}else if (type == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER) {//报损
									inventoryDetailsVo.setPeriodLossNums(quantity);
									inventoryDetailsVo.setPeriodLossMoneys(costTotal);
								}																								
							}
						}
					}
					
					//5.产品线--取库存调入 指定库房  
					String callInSql = "";
					List<Object> callinValues = new ArrayList<Object>();
					if(!isAllStore) {
						callInSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.product.categoryLevel1.category_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and his.flowOrder.toStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ?  and  his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? GROUP BY his.productBarcode.product.categoryLevel1.category_ID";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId};
						callinValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(callInSql, values, null, true);
					}
					if (callinValues != null) {
						for (Object object : callinValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int categoryLevel1Id = Common_util.getInt(object2[2]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(categoryLevel1Id);
								if(inventoryDetailsVo != null) {
								inventoryDetailsVo.setPeriodCallInNums(quantity);
								inventoryDetailsVo.setPeriodCallInMoneys(costTotal);								
							}
						}
					}
					
					//6.产品线--取调出  
					String outSql = "";
					List<Object> outValues = new ArrayList<Object>();
					if(!isAllStore) {
						outSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.product.categoryLevel1.category_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and his.flowOrder.fromStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ? and  his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ?  GROUP BY his.productBarcode.product.categoryLevel1.category_ID";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId};
						outValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(outSql, values, null, true);
					}
					if (outValues != null) {
						for (Object object : outValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int categoryLevel1Id = Common_util.getInt(object2[2]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(categoryLevel1Id);
								if(inventoryDetailsVo != null) {
									inventoryDetailsVo.setPeriodOutNums(quantity);
									inventoryDetailsVo.setPeriodOutMoneys(costTotal);									
							}							
						}
					}
					// 7.产品线--取上期数量和上期金额  
					String endHql;
					List<Object> inventoryEndData = new ArrayList<Object>();
					if (!isAllStore) {
						endHql = "SELECT his.productBarcode.product.categoryLevel1.category_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date <= ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+"  AND his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.categoryLevel1.category_ID";
						Object[] values = { staDate, yearId, quarterId ,belongTo};
						inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
					} else {
						endHql = "SELECT his.productBarcode.product.categoryLevel1.category_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE  his.date <= ?  and his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.categoryLevel1.category_ID";
						Object[] values = { staDate,yearId, quarterId,belongTo };
						inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
					}

					if (inventoryEndData != null) {
						for (Object object : inventoryEndData) {
							Object[] object2 = (Object[]) object;
							int categoryLevel1Id = Common_util.getInt(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							double costTotal = Common_util.getDouble(object2[2]);
							
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(categoryLevel1Id);
							inventoryDetailsVo.setBeforeAmount(quantity);
							inventoryDetailsVo.setBeforeAmountMoney(costTotal);	
							
						}
					}
					
					for(Integer categoryLevelID: hashMap.keySet()) {
						HqInventoryChangeDetailsVO vo = hashMap.get(categoryLevelID);
						vo.initAmountTo();
						headqInventoryVOList.add(vo);
					}
					
					
				} else if (categoryId == 0) {

					// @2. 展开所有品霞的库存信息 表示 categoryLevel1 != 0
					//1.货品类别-期末数量和金额
					HashMap<Integer, HqInventoryChangeDetailsVO> hashMap = new HashMap<Integer, HqInventoryChangeDetailsVO>();
					String hql;
					List<Object> inventoryData = new ArrayList<Object>();

					if (isAllStore) {
						hql = "SELECT his.productBarcode.product.category.category_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.category.category_ID";
						Object[] values = { eDate,yearId, quarterId, categoryLevelId,belongTo };

						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					} else {
						hql = "SELECT his.productBarcode.product.category.category_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+" AND   his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.category.category_ID";
						Object[] values = {eDate, yearId, quarterId, categoryLevelId ,belongTo};

						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					}

					if (inventoryData != null) {
						for (Object object : inventoryData) {
							Object[] object2 = (Object[]) object;
							int categoryIdDB = Common_util.getInt(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							double costTotal = Common_util.getDouble(object2[2]);

							Category catgory = categoryDaoImpl.get(categoryIdDB, true);
							String name = catgory.getCategory_Name();

							HqInventoryChangeDetailsVO inventoryDetailsVo = new HqInventoryChangeDetailsVO(parentId, name, quantity,
									costTotal, HeadqInventoryVO.STATE_CLOSED, storeIds, yearId, quarterId, brandId,
									categoryIdDB, categoryLevelId);
							inventoryDetailsVo.setTotalQuantity(quantity);
							inventoryDetailsVo.setTotalAmount(costTotal);	

							hashMap.put(categoryIdDB, inventoryDetailsVo);
						}
					}
					
					//2.货品类别--取采购模块
					List<Object> value_sale = new ArrayList<Object>();
					value_sale.add(staDate);
					value_sale.add(eDate);
					value_sale.add(BaseOrder.STATUS_COMPLETE);
					value_sale.add(belongTo);
					StringBuffer sql;
					if (!isAllStore) {
						value_sale.add(yearId);
						value_sale.add(quarterId);
						value_sale.add(categoryLevelId);
						 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity), p.order.type, p.pb.product.category.category_ID FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ? and p.order.status = ? and p.pb.product.brand.belong_To = ?  and p.order.store.id in "+Common_util.parseList2SQLString(stores)+" and p.pb.product.year.year_ID = ? AND p.pb.product.quarter.quarter_ID=? and p.pb.product.categoryLevel1.category_ID = ?  GROUP BY p.pb.product.category.category_ID,p.order.type");
					}else {
						value_sale.add(yearId);
						value_sale.add(quarterId);
						value_sale.add(categoryLevelId);
						 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity), p.order.type, p.pb.product.category.category_ID FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ? and p.order.status = ? and p.pb.product.brand.belong_To = ? and p.pb.product.year.year_ID = ?  AND p.pb.product.quarter.quarter_ID=? and p.pb.product.categoryLevel1.category_ID = ?  GROUP BY p.pb.product.category.category_ID, p.order.type");
					}
					List<Object> purchaseValues = purchaseOrderProductDaoImpl.executeHQLSelect(sql.toString(), value_sale.toArray(), null, true);
			
					if (purchaseValues != null){
						for (Object record : purchaseValues ){
							Object[] records = (Object[])record;
							int quantity = Common_util.getInt(records[0]);//数量
							double cost = Common_util.getDouble(records[1]);//成本
							int type = Common_util.getInt(records[2]);//类型
							int categoryID = Common_util.getInt(records[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(categoryID);
							if(inventoryDetailsVo != null) {
								if (type == PurchaseOrder.TYPE_PURCHASE) {//采购
									inventoryDetailsVo.setPeriodPurchaseNums(quantity);
									inventoryDetailsVo.setPeriodPurchaseMoneys(cost);
								}else if (type == PurchaseOrder.TYPE_RETURN) {//采购退货
									inventoryDetailsVo.setPeriodPurchaseReturnNums(quantity);
									inventoryDetailsVo.setPeriodPurchaseReturnMoneys(cost);
								}else if (type == PurchaseOrder.TYPE_FREE) {//采购赠送
									inventoryDetailsVo.setPeriodReceiveNums(quantity);
									inventoryDetailsVo.setPeriodReceiveMoneys(cost);
								}
							}													
						}														
					}
					
					//3.货品类别 --取销售模块
					List<Object> value_inventory = new ArrayList<Object>();
					value_inventory.add(staDate);
					value_inventory.add(eDate);
					value_inventory.add(InventoryOrder.STATUS_ACCOUNT_COMPLETE);//取审核完成的单据
					value_inventory.add(belongTo); 
					String criteria;
					if (!isAllStore) {
						value_inventory.add(yearId);
						value_inventory.add(quarterId);
						value_inventory.add(categoryLevelId);
						criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.product.category.category_ID  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.order.store.id in "+Common_util.parseList2SQLString(stores)+" and csp.productBarcode.product.year.year_ID = ? and csp.productBarcode.product.quarter.quarter_ID = ? and csp.productBarcode.product.categoryLevel1.category_ID = ?  GROUP BY csp.productBarcode.product.category.category_ID, csp.order.order_type";
					}else {
						value_inventory.add(yearId);
						value_inventory.add(quarterId);
						value_inventory.add(categoryLevelId);
						 criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.product.category.category_ID  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.productBarcode.product.year.year_ID = ? and csp.productBarcode.product.quarter.quarter_ID = ? and csp.productBarcode.product.categoryLevel1.category_ID =?  GROUP BY csp.productBarcode.product.category.category_ID, csp.order.order_type";
					}
					List<Object> inventoryValues = inventoryOrderProductDAOImpl.executeHQLSelect(criteria, value_inventory.toArray(), null, true);
					if (inventoryValues != null){
						for (Object record : inventoryValues ){
							Object[] records = (Object[])record;
							int quantity = Common_util.getInt(records[0]);
							double cost = Common_util.getDouble(records[1]);
							int type = Common_util.getInt(records[2]);
							int categoryID = Common_util.getInt(records[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(categoryID);
							if(inventoryDetailsVo != null) {					
								if (type == InventoryOrder.TYPE_SALES_ORDER_W) {//销售
									inventoryDetailsVo.setPeriodSaleNums(quantity);
									inventoryDetailsVo.setPeriodSaleMoneys(cost);										
								}else if(type == InventoryOrder.TYPE_SALES_RETURN_ORDER_W){//销售退货
									inventoryDetailsVo.setPeriodSaleReturnNums(quantity);
									inventoryDetailsVo.setPeriodSaleReturnMoneys(cost);
								}else if (type == InventoryOrder.TYPE_SALES_FREE_ORDER_W) {//销售赠送
									inventoryDetailsVo.setPeriodGiftNums(quantity);
									inventoryDetailsVo.setPeriodGiftMoneys(cost);
								}
							}
						}								
					}
					
					//4 货品类别--取库存报溢/报损
					String inventorySQL;	
					List<Object> overFlowValues = new ArrayList<Object>();
					if (!isAllStore) {
						inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.product.category.category_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and  his.flowOrder.storeId in "+Common_util.parseList2SQLString(stores)+" AND  his.productBarcode.product.brand.belong_To = ? and his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? AND his.productBarcode.product.categoryLevel1.category_ID = ?  GROUP BY his.productBarcode.product.category.category_ID, his.flowOrder.type";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId,categoryLevelId};
						overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
					} else {
						inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.product.category.category_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ?  AND  his.productBarcode.product.brand.belong_To = ? and his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? AND his.productBarcode.product.categoryLevel1.category_ID = ? GROUP BY his.productBarcode.product.category.category_ID, his.flowOrder.type";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId,categoryLevelId};
						overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
					}						
					if (overFlowValues != null) {
						for (Object object : overFlowValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int type = Common_util.getInt(object2[2]);
							int categoryID = Common_util.getInt(object2[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(categoryID);
							if(inventoryDetailsVo != null) {	
								if (type == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {//报溢
									inventoryDetailsVo.setPeriodOverflowNums(quantity);
									inventoryDetailsVo.setPeriodOverflowMoneys(costTotal);
								}else if (type == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER) {//报损
									inventoryDetailsVo.setPeriodLossNums(quantity);
									inventoryDetailsVo.setPeriodLossMoneys(costTotal);
								}																								
							}
						}
					}
					
					//5.货品类别--取库存调入 指定库房  
					String callInSql = "";
					List<Object> callinValues = new ArrayList<Object>();
					if(!isAllStore) {
						callInSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.product.category.category_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and his.flowOrder.toStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ?  and  his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? AND his.productBarcode.product.categoryLevel1.category_ID = ? GROUP BY his.productBarcode.product.category.category_ID";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId};
						callinValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(callInSql, values, null, true);
					}
					if (callinValues != null) {
						for (Object object : callinValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int categoryID = Common_util.getInt(object2[2]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(categoryID);
								if(inventoryDetailsVo != null) {
								inventoryDetailsVo.setPeriodCallInNums(quantity);
								inventoryDetailsVo.setPeriodCallInMoneys(costTotal);								
							}
						}
					}
					
					//6.货品类别--取调出  
					String outSql = "";
					List<Object> outValues = new ArrayList<Object>();
					if(!isAllStore) {
						outSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.product.category.category_ID FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and his.flowOrder.fromStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ? and  his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? AND his.productBarcode.product.categoryLevel1.category_ID = ?  GROUP BY his.productBarcode.product.category.category_ID";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId,categoryLevelId};
						outValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(outSql, values, null, true);
					}
					if (outValues != null) {
						for (Object object : outValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int categoryID = Common_util.getInt(object2[2]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(categoryID);
								if(inventoryDetailsVo != null) {
									inventoryDetailsVo.setPeriodOutNums(quantity);
									inventoryDetailsVo.setPeriodOutMoneys(costTotal);									
							}							
						}
					}
					// 7.货品类别--取上期数量和上期金额 
					String endHql;
					List<Object> inventoryEndData = new ArrayList<Object>();

					if (isAllStore) {
						endHql = "SELECT his.productBarcode.product.category.category_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.category.category_ID";
						Object[] values = { staDate,yearId, quarterId, categoryLevelId,belongTo };

						inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
					} else {
						endHql = "SELECT his.productBarcode.product.category.category_ID, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+" AND   his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.product.category.category_ID";
						Object[] values = {staDate, yearId, quarterId, categoryLevelId ,belongTo};

						inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
					}

					if (inventoryEndData != null) {
						for (Object object : inventoryEndData) {
							Object[] object2 = (Object[]) object;
							int categoryIdDB = Common_util.getInt(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							double costTotal = Common_util.getDouble(object2[2]);

							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(categoryIdDB);
							inventoryDetailsVo.setBeforeAmount(quantity);
							inventoryDetailsVo.setBeforeAmountMoney(costTotal);
						}
					}
					
					for(Integer categoryID: hashMap.keySet()) {
						HqInventoryChangeDetailsVO vo = hashMap.get(categoryID);
						vo.initAmountTo();
						headqInventoryVOList.add(vo);
					}	
				} else {
					// @2. 展开当前品霞的库存信息
					//1.货品类别-最后一级-期末数量和金额
					HashMap<Integer, HqInventoryChangeDetailsVO> hashMap = new HashMap<Integer, HqInventoryChangeDetailsVO>();
					String hql;
					List<Object> inventoryData = new ArrayList<Object>();
					if (isAllStore) {
						hql = "SELECT his.productBarcode.id,SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND  his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.category.category_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.id";
						Object[] values = {eDate,yearId, quarterId, categoryLevelId, categoryId ,belongTo};

						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					} else {
						hql = "SELECT his.productBarcode.id, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+" AND  his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND  his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.category.category_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.id";
						Object[] values = {eDate,  yearId, quarterId, categoryLevelId, categoryId ,belongTo};

						inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, values, null, true);
					}

					if (inventoryData != null) {
						for (Object object : inventoryData) {
							Object[] object2 = (Object[]) object;
							int pbId = Common_util.getInt(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							double costTotal = Common_util.getDouble(object2[2]);

							ProductBarcode pb = productBarcodeDaoImpl.get(pbId, true);
							Color color = pb.getColor();
							String colorName = "";
							if (color != null)
								colorName = color.getName();

							Brand brand = pb.getProduct().getBrand();
							String name = Common_util.cutProductCode(pb.getProduct().getProductCode()) + colorName + " "
									+ brand.getBrand_Name();

							HqInventoryChangeDetailsVO inventoryDetailsVo = new HqInventoryChangeDetailsVO(parentId, name, quantity,
									costTotal, HeadqInventoryVO.STATE_OPEN, storeIds, yearId, quarterId, brandId,
									categoryId, categoryLevelId);
							inventoryDetailsVo.setPbId(pbId);
							inventoryDetailsVo.setTotalQuantity(quantity);
							inventoryDetailsVo.setTotalAmount(costTotal);	
							hashMap.put(pbId,inventoryDetailsVo);

						}
					}
					
					//2.货品类别-最后一级--取采购模块
					List<Object> value_sale = new ArrayList<Object>();
					value_sale.add(staDate);
					value_sale.add(eDate);
					value_sale.add(BaseOrder.STATUS_COMPLETE);
					value_sale.add(belongTo);
					StringBuffer sql;
					if (!isAllStore) {
						value_sale.add(yearId);
						value_sale.add(quarterId);
						value_sale.add(categoryLevelId);
						value_sale.add(categoryId);
						 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity),p.order.type, p.pb.id FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ?  and p.order.status = ? and p.pb.product.brand.belong_To = ? and p.order.store.id in "+Common_util.parseList2SQLString(stores)+" and p.pb.product.year.year_ID = ? AND p.pb.product.quarter.quarter_ID=?  AND  p.pb.product.categoryLevel1.category_ID=? AND p.pb.product.category.category_ID=?  GROUP BY  p.pb.id, p.order.type ORDER BY p.pb.product.productCode ASC");
					}else {
						value_sale.add(yearId);
						value_sale.add(quarterId);
						value_sale.add(categoryLevelId);
						value_sale.add(categoryId);
						 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity),p.order.type, p.pb.id FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ? and p.order.status = ? and p.pb.product.brand.belong_To = ? and p.pb.product.year.year_ID = ?  AND p.pb.product.quarter.quarter_ID=? AND  p.pb.product.categoryLevel1.category_ID=? AND p.pb.product.category.category_ID=?  GROUP BY p.pb.id, p.order.type ORDER BY p.pb.product.productCode ASC");
					}
					List<Object> purchaseValues = purchaseOrderProductDaoImpl.executeHQLSelect(sql.toString(), value_sale.toArray(), null, true);
			
					if (purchaseValues != null){
						for (Object record : purchaseValues ){
							Object[] records = (Object[])record;
							int quantity = Common_util.getInt(records[0]);//数量
							double cost = Common_util.getDouble(records[1]);//成本
							int type = Common_util.getInt(records[2]);//类型
							int pbId = Common_util.getInt(records[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(pbId);
							if(inventoryDetailsVo != null) {
								if (type == PurchaseOrder.TYPE_PURCHASE) {//采购
									inventoryDetailsVo.setPeriodPurchaseNums(quantity);
									inventoryDetailsVo.setPeriodPurchaseMoneys(cost);
								}else if (type == PurchaseOrder.TYPE_RETURN) {//采购退货
									inventoryDetailsVo.setPeriodPurchaseReturnNums(quantity);
									inventoryDetailsVo.setPeriodPurchaseReturnMoneys(cost);
								}else if (type == PurchaseOrder.TYPE_FREE) {//采购赠送
									inventoryDetailsVo.setPeriodReceiveNums(quantity);
									inventoryDetailsVo.setPeriodReceiveMoneys(cost);
								}
							}													
						}														
					}
					
					//3.货品类别-最后一级 --取销售模块
					List<Object> value_inventory = new ArrayList<Object>();
					value_inventory.add(staDate);
					value_inventory.add(eDate);
					value_inventory.add(InventoryOrder.STATUS_ACCOUNT_COMPLETE);//取审核完成的单据
					value_inventory.add(belongTo); 
					String criteria;
					if (!isAllStore) {
						value_inventory.add(yearId);
						value_inventory.add(quarterId);
						value_inventory.add(categoryLevelId);
						value_inventory.add(categoryId);
						criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.id  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.order.store.id in "+Common_util.parseList2SQLString(stores)+" and csp.productBarcode.product.year.year_ID = ? and csp.productBarcode.product.quarter.quarter_ID = ?  AND  csp.productBarcode.product.categoryLevel1.category_ID=? AND csp.productBarcode.product.category.category_ID=? GROUP BY csp.productBarcode.id, csp.order.order_type";
					}else {
						value_inventory.add(yearId);
						value_inventory.add(quarterId);
						value_inventory.add(categoryLevelId);
						value_inventory.add(categoryId);
						 criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.id  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.productBarcode.product.year.year_ID = ? and csp.productBarcode.product.quarter.quarter_ID = ? AND  csp.productBarcode.product.categoryLevel1.category_ID=? AND csp.productBarcode.product.category.category_ID=? GROUP BY csp.productBarcode.id, csp.order.order_type";
					}
					List<Object> inventoryValues = inventoryOrderProductDAOImpl.executeHQLSelect(criteria, value_inventory.toArray(), null, true);
					if (inventoryValues != null){
						for (Object record : inventoryValues ){
							Object[] records = (Object[])record;
							int quantity = Common_util.getInt(records[0]);
							double cost = Common_util.getDouble(records[1]);
							int type = Common_util.getInt(records[2]);
							int pbId = Common_util.getInt(records[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(pbId);
							if(inventoryDetailsVo != null) {					
								if (type == InventoryOrder.TYPE_SALES_ORDER_W) {//销售
									inventoryDetailsVo.setPeriodSaleNums(quantity);
									inventoryDetailsVo.setPeriodSaleMoneys(cost);										
								}else if(type == InventoryOrder.TYPE_SALES_RETURN_ORDER_W){//销售退货
									inventoryDetailsVo.setPeriodSaleReturnNums(quantity);
									inventoryDetailsVo.setPeriodSaleReturnMoneys(cost);
								}else if (type == InventoryOrder.TYPE_SALES_FREE_ORDER_W) {//销售赠送
									inventoryDetailsVo.setPeriodGiftNums(quantity);
									inventoryDetailsVo.setPeriodGiftMoneys(cost);
								}
							}
						}								
					}
					
					//4 货品类别-最后一级--取库存报溢/报损
					String inventorySQL;	
					List<Object> overFlowValues = new ArrayList<Object>();
					if (!isAllStore) {
						inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.id FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and  his.flowOrder.storeId != "+Common_util.parseList2SQLString(stores)+" AND  his.productBarcode.product.brand.belong_To = ? and his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? AND  his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.category.category_ID=? GROUP BY his.productBarcode.id , his.flowOrder.type";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId,categoryLevelId,categoryId};
						overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
					} else {
						inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.id FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ?  AND  his.productBarcode.product.brand.belong_To = ? and his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? AND  his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.category.category_ID=? GROUP BY his.productBarcode.id , his.flowOrder.type";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId,categoryLevelId,categoryId};
						overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, values, null, true);
					}						
					if (overFlowValues != null) {
						for (Object object : overFlowValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int type = Common_util.getInt(object2[2]);
							int pbId = Common_util.getInt(object2[3]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(pbId);
							if(inventoryDetailsVo != null) {	
								if (type == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {//报溢
									inventoryDetailsVo.setPeriodOverflowNums(quantity);
									inventoryDetailsVo.setPeriodOverflowMoneys(costTotal);
								}else if (type == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER) {//报损
									inventoryDetailsVo.setPeriodLossNums(quantity);
									inventoryDetailsVo.setPeriodLossMoneys(costTotal);
								}																								
							}
						}
					}
					
					//5.货品类别-最后一级-取库存调入 指定库房  
					String callInSql = "";
					List<Object> callinValues = new ArrayList<Object>();
					if(!isAllStore) {
						callInSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.id FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and his.flowOrder.toStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ?  and  his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? AND  his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.category.category_ID=? GROUP BY his.productBarcode.id";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId,categoryLevelId,categoryId};
						callinValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(callInSql, values, null, true);
					}
					if (callinValues != null) {
						for (Object object : callinValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int pbId = Common_util.getInt(object2[2]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(pbId);
								if(inventoryDetailsVo != null) {
								inventoryDetailsVo.setPeriodCallInNums(quantity);
								inventoryDetailsVo.setPeriodCallInMoneys(costTotal);								
							}
						}
					}
					
					//6.货品类别-最后一级---取调出  
					String outSql = "";
					List<Object> outValues = new ArrayList<Object>();
					if(!isAllStore) {
						outSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.id FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  and his.flowOrder.status = ? and his.flowOrder.fromStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ? and  his.productBarcode.product.year.year_ID = ? and his.productBarcode.product.quarter.quarter_ID = ? AND  his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.category.category_ID=?  GROUP BY his.productBarcode.id ";
						Object[] values = { staDate,eDate,BaseOrder.STATUS_COMPLETE,belongTo,yearId,quarterId,categoryLevelId,categoryId};
						outValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(outSql, values, null, true);
					}
					if (outValues != null) {
						for (Object object : outValues) {
							Object[] object2 = (Object[]) object;
							
							double costTotal = Common_util.getDouble(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							int pbId = Common_util.getInt(object2[2]);
							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(pbId);
								if(inventoryDetailsVo != null) {
									inventoryDetailsVo.setPeriodOutNums(quantity);
									inventoryDetailsVo.setPeriodOutMoneys(costTotal);									
							}							
						}
					}
					// 7.货品类别-最后一级--取期末数量和期末金额  -- 合计信息
					String endHql;
					List<Object> inventoryEndData = new ArrayList<Object>();
					if (isAllStore) {
						endHql = "SELECT his.productBarcode.id,SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND  his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.category.category_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.id";
						Object[] values = {staDate,yearId, quarterId, categoryLevelId, categoryId ,belongTo};

						inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
					} else {
						endHql = "SELECT his.productBarcode.id, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+" AND  his.productBarcode.product.year.year_ID=? AND his.productBarcode.product.quarter.quarter_ID=? AND  his.productBarcode.product.categoryLevel1.category_ID=? AND his.productBarcode.product.category.category_ID=? AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.id";
						Object[] values = {staDate,  yearId, quarterId, categoryLevelId, categoryId ,belongTo};

						inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, values, null, true);
					}

					if (inventoryEndData != null) {
						for (Object object : inventoryEndData) {
							Object[] object2 = (Object[]) object;
							int pbId = Common_util.getInt(object2[0]);
							int quantity = Common_util.getInt(object2[1]);
							double costTotal = Common_util.getDouble(object2[2]);

							HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(pbId);
							inventoryDetailsVo.setBeforeAmount(quantity);
							inventoryDetailsVo.setBeforeAmountMoney(costTotal);
						
						}
					}
					
					
					for(Integer pbId: hashMap.keySet()) {
						HqInventoryChangeDetailsVO vo = hashMap.get(pbId);
						vo.initAmountTo();
						headqInventoryVOList.add(vo);
					}
				}
			}
		}


		response.setReturnValue(headqInventoryVOList);
		return response;
	}
	
	
	

	
	/**
	 * 下载进销变动信息
	 * @param parentId
	 * @param startDate
	 * @param endDate
	 * @param storeId
	 * @param yearId
	 * @param quarterId
	 * @param brandId
	 * @param categoryLevelId
	 * @param categoryId
	 * @param rptTypeId
	 * @param belongTo
	 * @param path
	 * @param loginUserInfor
	 * @return
	 */
	public Response getHeadqInventoryChangeDetails(int parentId, java.sql.Date startDate, java.sql.Date endDate,
			String storeIds, int yearId, int quarterId, int brandId, int categoryLevelId, int categoryId, int rptTypeId,
			int belongTo, String path, UserInfor loginUserInfor) {
		System.out.println(storeIds + "," + yearId + "," + quarterId + "," + brandId);
		Response response = new Response();
		boolean isAllStore = false;
		String storeName = "";
		//校验是否是全部库房				
		List<HeadQInventoryStore> headStores = headQInventoryStoreDAOImpl.getAll(true);
		String[] ids = null;
		List<Integer> stores = new ArrayList<Integer>();
		Set<Integer> set = new HashSet<Integer>();
		if (StringUtils.isNotBlank(storeIds)) {
			 ids = storeIds.split(",");	
			 for (int i = 0; i < ids.length; i++) {	
				 String idString = ids[i].trim();
				 set.add(Integer.valueOf(idString));
			 }
		}
		if (ids == null) {
			isAllStore = true;
			storeName = "所有库房";
		}else if (set.size() == headStores.size() ) {			
			isAllStore = true;		
			storeName = "所有库房";
		}else {
			for (Integer id: set) {						
				stores.add(id);	
				HeadQInventoryStore store  = headQInventoryStoreDAOImpl.get(id, true);
				if (store != null) {
					storeName += store.getName();
				}
			}
		}

		String hql;
		Date staDate = Common_util.formStartDate(startDate);
		Date eDate = Common_util.formEndDate(endDate);

			//上期数量金额
			HashMap<Integer, HqInventoryChangeDetailsVO> hashMap = new HashMap<Integer, HqInventoryChangeDetailsVO>();
			List<Object> inventoryData = new ArrayList<Object>();
			List<Object> before_value_sale = new ArrayList<Object>();
			before_value_sale.add(eDate);
			String beforeSql ="";
			if (yearId !=0) {
				beforeSql += " AND his.productBarcode.product.year.year_ID=? ";
				before_value_sale.add(yearId);
			}
			if (quarterId != 0) {
				beforeSql += " AND his.productBarcode.product.quarter.quarter_ID=?";
				before_value_sale.add(quarterId);
			}
			if (brandId !=0 ) {
				beforeSql += " AND his.productBarcode.product.brand.brand_ID=?";
				before_value_sale.add(brandId);
			}
			if (categoryLevelId !=0) {
				beforeSql += " AND his.productBarcode.product.categoryLevel1.category_ID=?";
				before_value_sale.add(categoryLevelId);
			}
			if (categoryId !=0) {
				beforeSql += " AND his.productBarcode.product.category.category_ID=?";
				before_value_sale.add(categoryId);
			}
			before_value_sale.add(belongTo);
			if (!isAllStore) {
				hql = "SELECT his.productBarcode.id, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.storeId in  "+Common_util.parseList2SQLString(stores)+ beforeSql+"   AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.id ORDER BY his.productBarcode.product.productCode ASC ";				
				inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, before_value_sale.toArray(), null, true);
			} else {
				hql = "SELECT his.productBarcode.id, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  "+beforeSql+"  AND his.productBarcode.product.brand.belong_To = ?  GROUP BY his.productBarcode.id ORDER BY his.productBarcode.product.productCode ASC ";				
				inventoryData = headQInventoryStockDAOImpl.executeHQLSelect(hql, before_value_sale.toArray(), null, true);
			}

			if (inventoryData != null) {
				for (Object object : inventoryData) {
					Object[] object2 = (Object[]) object;
					int pbId = Common_util.getInt(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					double costTotal = Common_util.getDouble(object2[2]);

					ProductBarcode pb = productBarcodeDaoImpl.get(pbId, true);
					Color color = pb.getColor();
					String colorName = "";
					if (color != null)
						colorName = color.getName();
					Product product = pb.getProduct();
					String gender = "";
					String sizeRange = "";

					Category category = product.getCategory();
					String name = Common_util.cutProductCode(pb.getProduct().getProductCode()) + colorName + " "
							+ gender + sizeRange + category.getCategory_Name();
					
					HqInventoryChangeDetailsVO inventoryDetailsVo = new HqInventoryChangeDetailsVO(parentId, name, quantity,
							costTotal, HeadqInventoryVO.STATE_OPEN, storeIds, yearId, quarterId, brandId,
							categoryId, categoryLevelId);
					inventoryDetailsVo.setPb(pb);
					inventoryDetailsVo.setPbId(pbId);
					inventoryDetailsVo.setTotalQuantity(quantity);
					inventoryDetailsVo.setTotalAmount(costTotal);	

					hashMap.put(pbId, inventoryDetailsVo);
				}
			}
			
			//2.采购模块
			List<Object> value_sale = new ArrayList<Object>();
			value_sale.add(staDate);
			value_sale.add(eDate);
			StringBuffer sql;
			String montageSql = "";

			if (yearId != 0) {
				montageSql += " and p.pb.product.year.year_ID = ? ";
				value_sale.add(yearId);
			}
			if (quarterId !=0) {
				montageSql += " AND p.pb.product.quarter.quarter_ID=?  ";
				value_sale.add(quarterId);
			}
			if (brandId !=0) {
				montageSql += " AND p.pb.product.brand.brand_ID=? ";
				value_sale.add(brandId);
			}
			if (categoryLevelId !=0) {
				montageSql += " AND p.pb.product.categoryLevel1.category_ID=? ";
				value_sale.add(brandId);
			}
			if (categoryId !=0) {
				montageSql += " AND p.pb.product.category.category_ID=? ";
				value_sale.add(brandId);
			}
			if (!isAllStore) {
				 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity),p.order.type, p.pb.id FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ?  and p.order.store.id in  "+Common_util.parseList2SQLString(stores)+montageSql+"  GROUP BY  p.pb.id, p.order.type ORDER BY p.pb.product.productCode ASC");
			}else {
				 sql = new StringBuffer("SELECT SUM(p.quantity), SUM(p.recCost * p.quantity),p.order.type, p.pb.id FROM PurchaseOrderProduct p WHERE  p.order.creationTime between ? and ?  "+montageSql+" GROUP BY p.pb.id, p.order.type ORDER BY p.pb.product.productCode ASC");
			}
			List<Object> purchaseValues = purchaseOrderProductDaoImpl.executeHQLSelect(sql.toString(), value_sale.toArray(), null, true);
	
			if (purchaseValues != null){
				for (Object record : purchaseValues ){
					Object[] records = (Object[])record;
					int quantity = Common_util.getInt(records[0]);//数量
					double cost = Common_util.getDouble(records[1]);//成本
					int type = Common_util.getInt(records[2]);//类型
					int brandIdDB = Common_util.getInt(records[3]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(brandIdDB);
					if(inventoryDetailsVo != null) {
						if (type == PurchaseOrder.TYPE_PURCHASE) {//采购
							inventoryDetailsVo.setPeriodPurchaseNums(quantity);
							inventoryDetailsVo.setPeriodPurchaseMoneys(cost);
						}else if (type == PurchaseOrder.TYPE_RETURN) {//采购退货
							inventoryDetailsVo.setPeriodPurchaseReturnNums(quantity);
							inventoryDetailsVo.setPeriodPurchaseReturnMoneys(cost);
						}else if (type == PurchaseOrder.TYPE_FREE) {//采购赠送
							inventoryDetailsVo.setPeriodReceiveNums(quantity);
							inventoryDetailsVo.setPeriodReceiveMoneys(cost);
						}
					}													
				}														
			}
			
			//3.销售模块
			List<Object> value_inventory = new ArrayList<Object>();
			value_inventory.add(staDate);
			value_inventory.add(eDate);
			value_inventory.add(InventoryOrder.STATUS_ACCOUNT_COMPLETE);//取审核完成的单据
			value_inventory.add(belongTo); 
			String criteria;
			String saleSql = "";

			if (yearId != 0) {
				saleSql += " and csp.productBarcode.product.year.year_ID = ? ";
				value_inventory.add(yearId);
			}
			if (quarterId !=0) {
				saleSql += " and csp.productBarcode.product.quarter.quarter_ID = ? ";
				value_inventory.add(quarterId);
			}
			if (brandId !=0) {
				saleSql += "  and csp.productBarcode.product.brand.brand_ID=? ";
				value_inventory.add(brandId);
			}
			if (categoryLevelId !=0) {
				saleSql += "  and csp.productBarcode.product.categoryLevel1.category_ID=? ";
				value_inventory.add(brandId);
			}
			if (categoryId !=0) {
				saleSql += "  and csp.productBarcode.product.category.category_ID=? ";
				value_inventory.add(brandId);
			}
			if (!isAllStore) {
				criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.id  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? and csp.order.store.id in "+Common_util.parseList2SQLString(stores)+saleSql+" GROUP BY csp.productBarcode.id, csp.order.order_type";
			}else {
				 criteria = "SELECT SUM(csp.quantity), SUM(csp.recCost * csp.quantity), csp.order.order_type,csp.productBarcode.id  FROM InventoryOrderProduct csp WHERE  csp.order.order_StartTime between ? and ?  AND csp.order.order_Status = ? AND csp.productBarcode.product.brand.belong_To = ? "+saleSql+"  GROUP BY csp.productBarcode.id, csp.order.order_type";
			}
			List<Object> inventoryValues = inventoryOrderProductDAOImpl.executeHQLSelect(criteria, value_inventory.toArray(), null, true);
			if (inventoryValues != null){
				for (Object record : inventoryValues ){
					Object[] records = (Object[])record;
					int quantity = Common_util.getInt(records[0]);
					double cost = Common_util.getDouble(records[1]);
					int type = Common_util.getInt(records[2]);
					int pbId = Common_util.getInt(records[3]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(pbId);
					if(inventoryDetailsVo != null) {					
						if (type == InventoryOrder.TYPE_SALES_ORDER_W) {//销售
							inventoryDetailsVo.setPeriodSaleNums(quantity);
							inventoryDetailsVo.setPeriodSaleMoneys(cost);										
						}else if(type == InventoryOrder.TYPE_SALES_RETURN_ORDER_W){//销售退货
							inventoryDetailsVo.setPeriodSaleReturnNums(quantity);
							inventoryDetailsVo.setPeriodSaleReturnMoneys(cost);
						}else if (type == InventoryOrder.TYPE_SALES_FREE_ORDER_W) {//销售赠送
							inventoryDetailsVo.setPeriodGiftNums(quantity);
							inventoryDetailsVo.setPeriodGiftMoneys(cost);
						}
					}
				}								
			}
			
			//4 库存报溢/报损
			String inventorySQL;	
			List<Object> value_overFlow = new ArrayList<Object>();//参数集合
			List<Object> overFlowValues = new ArrayList<Object>();//结果集合
			String ovreFlowSql = "";
			if (!isAllStore) {
				value_overFlow.add(staDate);
				value_overFlow.add(eDate);

				value_overFlow.add(belongTo);
			}else {
				value_overFlow.add(staDate);
				value_overFlow.add(eDate);
				value_overFlow.add(belongTo);
			}
			if (yearId != 0) {
				ovreFlowSql += " and his.productBarcode.product.year.year_ID = ? ";
				value_overFlow.add(yearId);
			}
			if (quarterId !=0) {
				ovreFlowSql += " and his.productBarcode.product.quarter.quarter_ID = ? ";
				value_overFlow.add(quarterId);
			}
			if (brandId !=0) {
				ovreFlowSql += "  and his.productBarcode.product.brand.brand_ID=? ";
				value_overFlow.add(brandId);
			}
			if (categoryLevelId !=0) {
				ovreFlowSql += "  and his.productBarcode.product.categoryLevel1.category_ID=? ";
				value_overFlow.add(brandId);
			}
			if (categoryId !=0) {
				ovreFlowSql += "  and his.productBarcode.product.category.category_ID=? ";
				value_overFlow.add(brandId);
			}
			if (!isAllStore) {
				inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.id FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ? and  his.flowOrder.storeId in "+Common_util.parseList2SQLString(stores)+" AND  his.productBarcode.product.brand.belong_To = ? "+ovreFlowSql+" GROUP BY his.productBarcode.id , his.flowOrder.type";
				overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, value_overFlow.toArray(), null, true);
			} else {
				inventorySQL = "SELECT  SUM(his.totalCost), SUM(his.quantity),his.flowOrder.type,his.productBarcode.id FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ?  AND  his.productBarcode.product.brand.belong_To = ? "+ovreFlowSql+"  GROUP BY his.productBarcode.id , his.flowOrder.type";
				overFlowValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(inventorySQL, value_overFlow.toArray(), null, true);
			}						
			if (overFlowValues != null) {
				for (Object object : overFlowValues) {
					Object[] object2 = (Object[]) object;
					
					double costTotal = Common_util.getDouble(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					int type = Common_util.getInt(object2[2]);
					int pbId = Common_util.getInt(object2[3]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(pbId);
					if(inventoryDetailsVo != null) {	
						if (type == HeadqInventoryFlowOrder.OVER_FLOW_ORDER) {//报溢
							inventoryDetailsVo.setPeriodOverflowNums(quantity);
							inventoryDetailsVo.setPeriodOverflowMoneys(costTotal);
						}else if (type == HeadqInventoryFlowOrder.FLOW_LOSS_ORDER) {//报损
							inventoryDetailsVo.setPeriodLossNums(quantity);
							inventoryDetailsVo.setPeriodLossMoneys(costTotal);
						}																								
					}
				}
			}
			
			//5.库存调入 指定库房  
			String callInSql = "";
			List<Object> callinList = new ArrayList<Object>();//结果集合
			List<Object> callinValues = new ArrayList<Object>();//参数集合
			callinValues.add(staDate);
			callinValues.add(eDate);
			
			callinValues.add(belongTo);

			String callInAppendSql = "";
			if (yearId !=0) {
				callInAppendSql += " and  his.productBarcode.product.year.year_ID = ?";
				callinValues.add(yearId);
			}
			if (quarterId !=0) {
				callInAppendSql += " and his.productBarcode.product.quarter.quarter_ID = ?";
				callinValues.add(quarterId);
			}
			if (brandId !=0) {
				callInAppendSql += "  and his.productBarcode.product.brand.brand_ID=? ";
				callinValues.add(brandId);
			}
			if (categoryLevelId !=0) {
				callInAppendSql += "  and his.productBarcode.product.categoryLevel1.category_ID=? ";
				callinValues.add(brandId);
			}
			if (categoryId !=0) {
				callInAppendSql += "  and his.productBarcode.product.category.category_ID=? ";
				callinValues.add(brandId);
			}
			if(!isAllStore) {
				callInSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.id FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ? and his.flowOrder.toStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ?  "+callInAppendSql+"  GROUP BY his.productBarcode.id";
				callinList = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(callInSql, callinValues.toArray(), null, true);
			}
			if (callinList != null) {
				for (Object object : callinList) {
					Object[] object2 = (Object[]) object;
					
					double costTotal = Common_util.getDouble(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					int brandIdDB = Common_util.getInt(object2[2]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(brandIdDB);
						if(inventoryDetailsVo != null) {
						inventoryDetailsVo.setPeriodCallInNums(quantity);
						inventoryDetailsVo.setPeriodCallInMoneys(costTotal);								
					}
				}
			}
			
			//6.调出  
			String outSql = "";
			List<Object> outList = new ArrayList<Object>();//结果集合
			List<Object> outValues = new ArrayList<Object>();//参数集合
			outValues.add(staDate);
			outValues.add(eDate);
			outValues.add(belongTo);
			String outAppendSql = "";
			if (yearId !=0) {
				outAppendSql += " and  his.productBarcode.product.year.year_ID = ?";
				outValues.add(yearId);
			}
			if (quarterId !=0) {
				outAppendSql += " and his.productBarcode.product.quarter.quarter_ID = ?";
				outValues.add(quarterId);
			}
			if (brandId !=0) {
				outAppendSql += "  and his.productBarcode.product.brand.brand_ID=? ";
				outValues.add(brandId);
			}
			if (categoryLevelId !=0) {
				outAppendSql += "  and his.productBarcode.product.categoryLevel1.category_ID=? ";
				outValues.add(brandId);
			}
			if (categoryId !=0) {
				outAppendSql += "  and his.productBarcode.product.category.category_ID=? ";
				outValues.add(brandId);
			}
			if(!isAllStore) {
				outSql = "SELECT  SUM(his.totalCost), SUM(his.quantity), his.productBarcode.id FROM HeadqInventoryFlowOrderProduct AS his WHERE his.flowOrder.orderDate between ? and ? and his.flowOrder.fromStore.id in "+Common_util.parseList2SQLString(stores)+" and his.flowOrder.type = "+HeadqInventoryFlowOrder.INVENTORY_TRANSFER_ORDER+"  AND  his.productBarcode.product.brand.belong_To = ?  "+outAppendSql+" GROUP BY his.productBarcode.id ";
				outValues = headqInventoryFlowOrderProductDaoImpl.executeHQLSelect(outSql, outValues.toArray(), null, true);
			}
			if (outList != null) {
				for (Object object : outList) {
					Object[] object2 = (Object[]) object;
					
					double costTotal = Common_util.getDouble(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					int brandIdDB = Common_util.getInt(object2[2]);
					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(brandIdDB);
						if(inventoryDetailsVo != null) {
							inventoryDetailsVo.setPeriodOutNums(quantity);
							inventoryDetailsVo.setPeriodOutMoneys(costTotal);									
					}							
				}
			}
			// 7.上期数量和上期金额 
			String endHql;
			List<Object> inventoryEndData = new ArrayList<Object>();//结果集合
			List<Object> inventoryEndvalues = new ArrayList<Object>();//参数集合
			inventoryEndvalues.add(staDate);
			String endAppendSql = "";
			if (yearId !=0) {
				endAppendSql += " and  his.productBarcode.product.year.year_ID = ?";
				inventoryEndvalues.add(yearId);
			}
			if (quarterId !=0) {
				endAppendSql += " and his.productBarcode.product.quarter.quarter_ID = ?";
				inventoryEndvalues.add(quarterId);
			}
			if (brandId !=0) {
				endAppendSql += "  and his.productBarcode.product.brand.brand_ID=? ";
				inventoryEndvalues.add(brandId);
			}
			if (categoryLevelId !=0) {
				endAppendSql += "  and his.productBarcode.product.categoryLevel1.category_ID=? ";
				inventoryEndvalues.add(brandId);
			}
			if (categoryId !=0) {
				endAppendSql += "  and his.productBarcode.product.category.category_ID=? ";
				inventoryEndvalues.add(brandId);
			}
			
			inventoryEndvalues.add(belongTo);

			if (!isAllStore) {
				endHql = "SELECT his.productBarcode.id, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  and his.storeId in "+Common_util.parseList2SQLString(stores)+endAppendSql+"  AND his.productBarcode.product.brand.belong_To = ? GROUP BY his.productBarcode.id ORDER BY his.productBarcode.product.productCode ASC ";
				inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, inventoryEndvalues.toArray(), null, true);
			} else {
				endHql = "SELECT his.productBarcode.id, SUM(quantity),SUM(costTotal) FROM HeadQInventoryStock AS his WHERE his.date < ?  "+endAppendSql+"  AND his.productBarcode.product.brand.belong_To = ?  GROUP BY his.productBarcode.id ORDER BY his.productBarcode.product.productCode ASC ";
				inventoryEndData = headQInventoryStockDAOImpl.executeHQLSelect(endHql, inventoryEndvalues.toArray(), null, true);
			}

			if (inventoryEndData != null) {
				for (Object object : inventoryEndData) {
					Object[] object2 = (Object[]) object;
					int pbId = Common_util.getInt(object2[0]);
					int quantity = Common_util.getInt(object2[1]);
					double costTotal = Common_util.getDouble(object2[2]);

					HqInventoryChangeDetailsVO inventoryDetailsVo = hashMap.get(pbId);
					inventoryDetailsVo.setBeforeAmount(quantity);
					inventoryDetailsVo.setBeforeAmountMoney(costTotal);

				}
			}	
			
			List<HqInventoryChangeDetailsVO> list = new ArrayList<HqInventoryChangeDetailsVO>();
			for(Integer quarterInteger: hashMap.keySet()) {
				HqInventoryChangeDetailsVO vo = hashMap.get(quarterInteger);
				vo.initAmountTo();
				vo.toString();
				list.add(vo);
			}	
			
			HeadqInventoryChangeReportTemplate headqInventoryReportTemplate;
			try {
				headqInventoryReportTemplate = new HeadqInventoryChangeReportTemplate(list, storeName, path);
				HSSFWorkbook wb = headqInventoryReportTemplate.processDetails();

				ByteArrayInputStream byteArrayInputStream = ExcelUtil.convertExcelToInputStream(wb);

				response.setReturnValue(byteArrayInputStream);
				response.setReturnCode(Response.SUCCESS);
			} catch (IOException e) {
				response.setFail(e.getMessage());
				e.printStackTrace();
			}

			return response;		
	}

	
	/**
	 * 下载层级报表
	 * @param list
	 * @return
	 */
	public Response getHeadqInventoryLevelReport(List<HqInventoryChangeDetailsVO> list,String storeIds,String path) {
		Response response = new Response();
		HeadqInventoryChangeReportTemplate headqInventoryReportTemplate;
		String storeName = "";		
		String[] ids = null;

		if (StringUtils.isNotBlank(storeIds)) {
			 ids = storeIds.split(",");	
			 for (int i = 0; i < ids.length; i++) {	
				 String idString = ids[i].trim();
				 if (StringUtils.isNotBlank(idString)) {
					 HeadQInventoryStore store  = headQInventoryStoreDAOImpl.get(Integer.valueOf(idString), true);
						if (store != null) {
							storeName += store.getName() + ",";
						}
				}				 
			 }
		}else {
			storeName = "所有库房";
		}
		
		
		try {
			headqInventoryReportTemplate = new HeadqInventoryChangeReportTemplate(list, storeName, path);
			HSSFWorkbook wb = headqInventoryReportTemplate.process();

			ByteArrayInputStream byteArrayInputStream = ExcelUtil.convertExcelToInputStream(wb);

			response.setReturnValue(byteArrayInputStream);
			response.setReturnCode(Response.SUCCESS);
		} catch (IOException e) {
			response.setFail(e.getMessage());
			e.printStackTrace();
		}

		return response;	
	}


	public Response selectOrderProducts(HeadqInventoryFlowOrder order) {
		Response response = new Response();
		Map dataMap = new HashMap();
		List<InventoryOrderProductsVO> vos = new ArrayList<InventoryOrderProductsVO>();
		
		if (order.getId() != Common_util.ALL_RECORD_NEW) {
			HeadqInventoryFlowOrder flowOrder = headqInventoryFlowOrderDaoImpl.get(order.getId(), true);
			List<HeadqInventoryFlowOrderProduct> list = headqInventoryFlowOrderProductDaoImpl.selectProductsByOrderId(order.getId());
			if (list.size() != Common_util.ALL_RECORD_NEW && flowOrder != null) {
				int id = 1;//排序用
				for (HeadqInventoryFlowOrderProduct product : list) {
					InventoryOrderProductsVO vo = new InventoryOrderProductsVO();
					vo.setOrderType(flowOrder.getType());
					vo.setId(id);
					vo.setPbId(Integer.toString(product.getProductBarcode().getId()));
					vo.setBarcode(product.getProductBarcode().getBarcode());
					vo.setProductCode(product.getProductBarcode().getProduct().getProductCode());
					
					Color color = product.getProductBarcode().getColor();
					if (color != null)
					   vo.setColorName(color.getName());
					vo.setBrand(product.getProductBarcode().getProduct().getBrand().getBrand_Name());
					vo.setCategoryLevel(product.getProductBarcode().getProduct().getCategoryLevel1().getCategory_Name());
					vo.setCategory(product.getProductBarcode().getProduct().getCategory().getCategory_Name());
					vo.setYear(product.getProductBarcode().getProduct().getYear().getYear());
					vo.setQuarter(product.getProductBarcode().getProduct().getQuarter().getQuarter_Name());
					vo.setUnit(product.getProductBarcode().getProduct().getUnit());
					vo.setSalesPrice(product.getProductBarcode().getProduct().getSalesPrice());
					vo.setTotalWholePrice(product.getProductBarcode().getProduct().getSalesPrice() * product.getQuantity());
					vo.setQuantity(product.getQuantity());
					vo.setTotalCost(product.getTotalCost());
					int inventoryQ =  headQInventoryStockDAOImpl.getProductStock(product.getProductBarcode().getId() , flowOrder.getStoreId(), true);
					vo.setInventoryQ(inventoryQ);
					vo.setScanNums(product.getScanNums());//扫描次数
					vo.setComment(product.getComment());
					vos.add(vo);
					id++;
				}
			}
		}

		dataMap.put("rows", vos);
		response.setReturnValue(dataMap);
		response.setReturnCode(Response.SUCCESS);
		return response;
	}

	
	public Response selectOrderProductDetails(HeadqInventoryFlowOrder order) {
		Response response = new Response();
		Map dataMap = new HashMap();
		List<InventoryOrderProductsVO> vos = new ArrayList<InventoryOrderProductsVO>();
		List<InventoryOrderProductsVO> footers = new ArrayList<InventoryOrderProductsVO>();
		InventoryOrderProductsVO footer = new InventoryOrderProductsVO();
		if (order.getId() != Common_util.ALL_RECORD_NEW) {
			HeadqInventoryFlowOrder flowOrder = headqInventoryFlowOrderDaoImpl.get(order.getId(), true);
			List<HeadqInventoryFlowOrderProduct> list = headqInventoryFlowOrderProductDaoImpl.selectProductsByOrderId(order.getId());
			if (list.size() != Common_util.ALL_RECORD_NEW && flowOrder != null) {
				int id = 1;//排序用
				for (HeadqInventoryFlowOrderProduct product : list) {
					InventoryOrderProductsVO vo = new InventoryOrderProductsVO();
					vo.setId(id);
					vo.setPbId(Integer.toString(product.getProductBarcode().getId()));
					vo.setBarcode(product.getProductBarcode().getBarcode());
					vo.setProductCode(product.getProductBarcode().getProduct().getProductCode());
					
					Color color = product.getProductBarcode().getColor();
					if (color != null )
					   vo.setColorName(color.getName());
					vo.setBrand(product.getProductBarcode().getProduct().getBrand().getBrand_Name());
					vo.setCategoryLevel(product.getProductBarcode().getProduct().getCategoryLevel1().getCategory_Name());
					vo.setCategory(product.getProductBarcode().getProduct().getCategory().getCategory_Name());
					vo.setYear(product.getProductBarcode().getProduct().getYear().getYear());
					vo.setQuarter(product.getProductBarcode().getProduct().getQuarter().getQuarter_Name());
					vo.setUnit(product.getProductBarcode().getProduct().getUnit());
					vo.setSalesPrice(product.getProductBarcode().getProduct().getSalesPrice());
					vo.setTotalWholePrice(product.getProductBarcode().getProduct().getSalesPrice() * product.getQuantity());
					vo.setQuantity(product.getQuantity());
					vo.setTotalCost(product.getTotalCost());
					vo.setInventoryQ(product.getInventoryQ());
					vo.setScanNums(product.getScanNums());//扫描次数
					vo.setComment(product.getComment());
					vos.add(vo);
					footer.setYear("合计");
					footer.setQuantity(footer.getQuantity()+product.getQuantity());
					footer.setInventoryQ(footer.getInventoryQ()+product.getInventoryQ());
					footer.setTotalWholePrice(footer.getTotalWholePrice() + vo.getTotalWholePrice());
					footer.setScanNums(footer.getScanNums()+product.getScanNums());
					id++;
				}
			}
		}
		footers.add(footer);
		dataMap.put("footer", footers);
		dataMap.put("rows", vos);
		response.setReturnValue(dataMap);
		response.setReturnCode(Response.SUCCESS);
		return response;
	}

	/**
	 * 创建库房信息combobox 下拉框信息
	 * @return
	 */
	public List<ComboboxVO> selectInventoryStores() {
		List<HeadQInventoryStore> headStores = headQInventoryStoreDAOImpl.getAll(true);
		List<ComboboxVO> vos = new ArrayList<ComboboxVO>();
		for (HeadQInventoryStore headQInventoryStore : headStores) {
			ComboboxVO vo = new ComboboxVO();
			vo.setId(headQInventoryStore.getId());
			vo.setText(headQInventoryStore.getName());
			vos.add(vo);
		}
		return vos;
	}
}
